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.
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With