Is there a way to scale your HTML canvas to the browser window width/height but not scale the contents within it? Say I was creating Asteroids and want to use the entire browser window but don't want the rocks and ship to scale up/down when I resize the window.
Asked
Active
Viewed 1.0k times
12
-
asteroids, rocks and ship.. wut? – Wouter Dorgelo Dec 30 '11 at 22:52
-
1+1 for a good question. I believe I have the answer you need. – Phrogz Dec 31 '11 at 06:00
1 Answers
28
Do not use CSS to scale your canvas. That will scale the pixels in the canvas up/down.
Instead, watch for a
resize
event on an appropriate element (e.g. the window) and then change the.width
and.height
properties of the canvas appropriately in JavaScript. This will change how many pixels you are drawing with.Continue to use the same fixed-size drawing commands you always use. Object will stay that same pixel size on screen.
To keep your contents centered on the screen, you may want to treat 0,0 as the center of the canvas by using
translate()
on the context right after you resize it. For example:var ctx = document.querySelector('#mycanvas').getContext('2d'); window.addEventListener('resize',function(){ var width = calculateDesiredWidth(); // your code here var height = calculateDesiredHeight(); // your code here ctx.canvas.width = width; ctx.canvas.height = height; ctx.translate(width/2,height/2); // now 0,0 is the center of the canvas. },false);
Full working example: http://phrogz.net/tmp/canvas-fullscreen.html

Phrogz
- 296,393
- 112
- 651
- 745
-
-
Phrogz, thanks so much for the answer and the working example. That helps tremendously! – Jammy Jan 04 '12 at 03:24