Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 208
Jospehus Chou Avatar asked Feb 11 '15 07:02

Jospehus Chou


People also ask

How do you change the height and width of a canvas?

The width attribute specifies the width of the <canvas> element, in pixels. Tip: Use the height attribute to specify the height of the <canvas> element, in pixels. Tip: Each time the height or width of a canvas is re-set, the canvas content will be cleared (see example at bottom of page).


1 Answers

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.

like image 81
Lanny Avatar answered Sep 18 '22 09:09

Lanny