How should I create a responsive canvas with createJs to adapt different mobile device's screens?

Jospehus Chou picture Jospehus Chou · Feb 11, 2015 · Viewed 8.7k times · Source

I want to develop a html5 mobile game. As you know, the screens of mobile devices are different size, so I want to create a responsive canvas so that it can adapt different screen.

Answer

Lanny picture Lanny · Feb 11, 2015

The simplest way is to resize your canvas with JavaScript, based on the viewport, and then reflow the contents.

var w = $("#container").width();
var h = $("#container").height();

stage.canvas.width = w;
stage.canvas.height = h;

// Simple "fit-to-screen" scaling
var ratio = contentWidth / contentHeight; // Use the "default" size of the content you have.
var windowRatio = w/h;
var scale = w/contentWidth;
if (windowRatio > ratio) {
    scale = h/contentHeight;
}
content.scaleX = content.scaleY = scale;

Here is a simple example. It is a bit different than the sample code to make it work in a resizing window. http://jsfiddle.net/lannymcnie/4yy08pax/

If you are dealing with mobile devices, there are some other things to consider (they auto-scale canvases to account for their high DPI).

Hope this helps.