Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 850
Jammy Avatar asked Dec 30 '11 22:12

Jammy


1 Answers

  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

like image 162
Phrogz Avatar answered Oct 20 '22 08:10

Phrogz