How can I automatically scale the HTML5 <canvas>
element to fit the page?
For example, I can get a <div>
to scale by setting the height
and width
properties to 100%, but a <canvas>
won't scale, will it?
How can I automatically scale the HTML5 <canvas>
element to fit the page?
For example, I can get a <div>
to scale by setting the height
and width
properties to 100%, but a <canvas>
won't scale, will it?
The following solution worked for me the best. Since I'm relatively new to coding, I like to have visual confirmation that something is working the way I expect it to. I found it at the following site: http://htmlcheats.com/html/resize-the-html5-canvas-dyamically/
Here's the code:
The blue border shows you the edge of the resizing canvas, and is always along the edge of the window, visible on all 4 sides, which was NOT the case for some of the other above answers. Hope it helps.
Unless you want the canvas to upscale your image data automatically (that's what James Black's answer talks about, but it won't look pretty), you have to resize it yourself and redraw the image. Centering a canvas
I think this is what should we exactly do: http://www.html5rocks.com/en/tutorials/casestudies/gopherwoord-studios-resizing-html5-games/
Using jQuery you can track the window resize and change the width of your canvas using jQuery as well.
Something like that
Setting the canvas coordinate space width and height based on the browser client's dimensions requires you to resize and redraw whenever the browser is resized.
A less convoluted solution is to maintain the drawable dimensions in Javascript variables, but set the canvas dimensions based on the screen.width, screen.height dimensions. Use CSS to fit:
The browser window generally won't ever be larger than the screen itself (except where the screen resolution is misreported, as it could be with non-matching dual monitors), so the background won't show and pixel proportions won't vary. The canvas pixels will be directly proportional to the screen resolution unless you use CSS to scale the canvas.