5

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.

Jospehus Chou
  • 117
  • 1
  • 10

1 Answers1

8

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.

Lanny
  • 11,244
  • 1
  • 22
  • 30
  • What if you have multiple shapes? How can you get the contentWidth / contentHeight of each? – PDoria Sep 30 '15 at 16:49
  • 1
    Do you want to resize every element to fit the screen? Ideally you just have a single piece of content that you scale, and you know the "default" size of that content, which you use in the approach above. The example uses the `exportRoot`, because it has a nominal size it was created at. – Lanny Sep 30 '15 at 17:57
  • I see what you mean. Imagine your window, or content area is 500 x 300. You stick that into contentWidth / contentHeight - because you only need to calculate the ratio!! Thanks for your response. – PDoria Sep 30 '15 at 20:02
  • @Lanny Could I not just resize the entire stage instead of having another content layer? – FluffyBeing Aug 23 '16 at 19:25
  • 1
    Resizing stage has some possible side effects. I recommend a sub-container. It has almost no overhead (one additional context transform), and lets you continue to visualize your stage as a representation of the canvas. – Lanny Aug 23 '16 at 20:33
  • 1
    @Lanny #container in this case is the DOM element that wraps the canvas /stage and then "content" is an actual easeljs Container object that is a child of the stage correct? – FluffyBeing Aug 25 '16 at 19:59