简体   繁体   English

HTML5 Canvas的调整大小功能

[英]Resize function for HTML5 Canvas

I managed to put together a dynamically resizing HTML5 Canvas but it has issues. 我设法将动态调整大小的HTML5 Canvas放在一起,但是出现了问题。 For instance, it only scales the height, not the width too. 例如,它仅缩放高度,而不缩放宽度。 My canvas has width of 900px and height of 850px . 我的画布的宽度为900px ,高度为850px Another issue is that it enlarges the canvas too, way beyond it's defined width and height. 另一个问题是它也会扩大画布,使其超出定义的宽度和高度。

What am I doing wrong? 我究竟做错了什么?

Here's what I 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 attributes like so: canvas.width = width; 如果我尝试@havex所说的,请像这样更改属性: canvas.width = width; and canvas.height = height; canvas.height = height; instead of canvas.style.width = width+'px'; 而不是canvas.style.width = width+'px'; and canvas.style.height = height+'px'; canvas.style.height = height+'px'; what I get is a resizable box BUT NOT the animation. 我得到的是一个可调整大小的框,但不是动画。 See picture for reference : 参考图片:

在此处输入图片说明

I can't explain why that is happening because it's 4:30 in the morning and I haven't slept yet, but change these and it should work (you can remove the borders): 我无法解释为什么会发生这种情况,因为它是凌晨4点30分,我还没有睡过,但是请更改它们,它应该可以工作(您可以删除边框):

HTML HTML

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

CSS 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/ http://jsfiddle.net/Ln5z1zab/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM