Resize function for HTML5 canvas

I managed to compile a dynamically resizing HTML5 canvas, but it has problems. For example, it scales only height, not width. My canvas has a width of 900px and a height of 850px . Another problem is that it also enlarges the canvas without limiting its width and height.

What am I doing wrong?

Here is what I have tried so far:

 var canvas, stage, exportRoot; function init() { createjs.MotionGuidePlugin.install(); canvas = document.getElementById("canvas"); exportRoot = new lib.Hat_finale(); stage = new createjs.Stage(canvas); stage.addChild(exportRoot); stage.update(); createjs.Ticker.setFPS(24); createjs.Ticker.addEventListener("tick", stage); } function resize() { var height = window.innerHeight; var ratio = canvas.width / canvas.height; var width = height * ratio; canvas.style.width = width + 'px'; canvas.style.height = height + 'px'; } window.addEventListener('load', resize, false); window.addEventListener('resize', resize, false); 
 #container { margin: 0 auto; max-width: 900px; max-height: 850px; } 
 <div id="container"> <canvas id="canvas" width="900" height="850" style="background-color:#ffffff"></canvas> </div> 

UPDATE:

If I try what @havex said, changing the following attributes: canvas.width = width; and canvas.height = height; instead of canvas.style.width = width+'px'; and canvas.style.height = height+'px'; what i get is resizable, not animation. See illustration for reference:

enter image description here

+1
javascript html5 canvas
source share
1 answer

I can’t explain why this happens because it is 4:30 in the morning and I haven’t slept yet, but changed them and it should work (you can remove the borders):

HTML

 <div id="container"> <canvas id="canvas" style="background-color:#ffffff"></canvas> </div> 

CSS

 #container{ margin:0 auto; width:900px; height:850px; border: 1px solid black; } canvas { width: 900px; height: 850px; border: 1px solid red; } 

http://jsfiddle.net/Ln5z1zab/

0
source share

All Articles