Scale HTML canvas to browser window size but don't scale elements within the canvas

后端 未结 1 652
小鲜肉
小鲜肉 2021-02-02 01:40

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

相关标签:
1条回答
  • 2021-02-02 02:03
    1. Do not use CSS to scale your canvas. That will scale the pixels in the canvas up/down.

    2. 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.

    3. Continue to use the same fixed-size drawing commands you always use. Object will stay that same pixel size on screen.

    4. 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

    0 讨论(0)
提交回复
热议问题