Version 0.3 on mobile screenshot.

Vector Racer 0.3 – Responsive canvas

Vector Racer has reached version 0.3 and the major improvement in this release is the mobile UI.

The game runs in a HTML Canvas element, and the canvas element need to have a width and height defined in pixels. That goes against responsive web design for mobile which relies heavily on relative units for layout.

In short: On mobile, you want to be able to fill the width of the screen regardless of differences in screen resolution:

Version 0.3 on mobile screenshot.

Responsive canvas through scale()

For a while, I didn’t think that the canvas could become responsive since the canvas element is so pixel bound.

Every canvas method and, subsequently, all my game logic is pixel based. Having to recalculate would be a nightmare, I thought.

Enter the scale() method:

The scale() method lets me keep all my game logic untouched and just scale the drawings on the canvas and the width and height of the element.

To scale the canvas using JavaScript, I’m doing this if the screen is less than 800px:

var resizeCanvas = function() {
  var game = document.getElementById("game");
  var canvas = game.getContext("2d");

  var screenWidth = screen.width;
  var gameWidth = game.width;
  var gameHeight = game.height;
  var widthRatio = screenWidth / gameWidth;
  game.width = gameWidth * widthRatio;
  game.height = gameHeight * widthRatio;
  canvas.scale(widthRatio, widthRatio);

Basically, I:

  • Get width of screen on device (360px on Nexus 5)
  • Get a ratio by dividing that by the original game width (800px)
  • Scale width and height using the ratio (0.45 on Nexus 5)
  • Set the width and height attribute of the HTML canvas element itself accordingly

This allows me to incorporate the canvas element into a responsive layout and thus create a sensible, responsive layout for all screen sizes.