Resize canvas

Shows how to adjust the canvas to fit the screen, with two configurable options

HTML

<body scroll="no" style="overflow: hidden">
  <div id="gameArea">
    <canvas id="gameCanvas" />
  </div>
</body>

CSS

#gameArea {
  position: absolute;
  left: 50%;
  top: 50%;
}

#gameCanvas {
  width: 100%;
  height: 100%;
}

JavaScript

(function(limit_canvas_size, stretch_to_fit) {

  var canvas = document.getElementById('gameCanvas');
  var game_area = document.getElementById('gameArea');

  // try with different resolutions !
  canvas.width = 600;
  canvas.height = 600;

  var aspect_ratio = canvas.width / canvas.height;

  var context = canvas.getContext('2d');

  function draw() {
    context.save();
    context.fillRect(0, 0, canvas.width, canvas.height);
    context.fillStyle = "red";
    context.fillRect(canvas.width / 4, canvas.height / 4, canvas.width / 2, canvas.height / 2);
    context.restore();
  }

  function resize() {
    // start with canvas original aspect ratio
    var widthToHeight = aspect_ratio;
    var newWidthToHeight = aspect_ratio;

    // cache the window dimensions
    var newWidth = window.innerWidth,
      newHeight = window.innerHeight;

    if (limit_canvas_size) {
      // fit smaller screen entirely but maintain the resolution on bigger screens
      newWidth = newWidth <= canvas.width ? newWidth : canvas.width;
      newHeight = newHeight <= canvas.height ? newHeight : canvas.height;
      // this will be the visual aspect ratio
      newWidthToHeight = newWidth / newHeight;
    }

    if (stretch_to_fit) {
      // overwrite the current canvas aspect ratio to fit the entire screen
      widthToHeight = window.innerWidth / window.innerHeight;
    }

    // special case (only fit the screen if window is smaller than resolution)
    if (stretch_to_fit && limit_canvas_size) {
      newWidth = canvas.width;
      newHeight = canvas.height;
      newWidth = window.innerWidth <= newWidth ? window.innerWidth : newWidth;
      newHeight = window.innerHeight <= newHeight ? window.innerHeight : newHeight;
      // this will be the visual aspect ratio
      widthToHeight = newWidth / newHeight;
    } else {
      // this will be the visual aspect ratio 
      newWidthToHeight = newWidth / newHeight;
    }

    // scale the game area using CSS		
    if (newWidthToHeight >...