Relatively sizing HTML Canvas

The canvas width and height attributes are separate from the same canvas's width and height styles. The width and height attributes are the size of the canvas's rendering surface, in pixels, whereas its styles choose a location in the document where the browser should draw the content from the rendering surface. It just so happens that the default value for the width and height styles, if they're not specified, is the rendering surface's width and height. So you're right about #1: there's no reason to wrap it in a div. You can set percentage values for all of the styles on your canvas element, just like any other element.

For #3, it's pretty easy (and cross-browser) to get the size of things with clientWidth and clientHeight, as long as you're not using padding on your canvas element.

I coded up the slightly simplified version here.

For #4, you're right about being out of luck. It's possible to check before setting width and height and leave the canvas alone if it doesn't need resizing, which would eliminate some of the redraws, but you can't get rid of all of them.

EDIT: Portman pointed out I messed up the centering style. Updated version here.


Like said by sethobrien a canvas element has TWO pairs width/height of attributes.

  1. canvas.width / canvas.height are about the size in pixel of the buffer that will contains the result of drawing commands.

  2. canvas.style.width / canvas.style.height are about the size used to show the canvas object in the browser window and they can be in any of the units supported by css.

You can indeed set canvas.width and canvas.height just once, do the drawing in the canvas, setting the style size parameters in percentage and then forget about redrawing the canvas content. Of course this means that the browser will just do the scaling itself like for a regular image loaded from the network so the visible result will show pixel scaling artifacts.

You need to redraw the canvas content after the resize of the canvas element only if you want pixel-perfect results.


Alright. Here is the technique that i ve used to implement the same.

Suppose you have the canvas height=400, for the window's height=480, and you want to change the height of it relatively if the window's height changes to 640.

canvas = document.getElementById("canvas"); 
canvas.height=window.innerHeight*400/480;

p.s: do not initialize the height of the canvas inside the html tag.

Make use of 'window.innerHeight' (which returns the height of the browser's window.. similarly 'window.innerWidth') any where you want to calculate the relative positions on the window.

Hope you got what you needed.