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
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);