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.
How should I create a responsive canvas with createJs to adapt different mobile device's screens?
Asked Answered
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.
What if you have multiple shapes? How can you get the contentWidth / contentHeight of each? –
Boatright
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. –
Rabblerouser 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. –
Boatright
@Rabblerouser Could I not just resize the entire stage instead of having another content layer? –
Bushido
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. –
Rabblerouser
@Rabblerouser #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? –
Bushido
© 2022 - 2024 — McMap. All rights reserved.