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.
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
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);