调整HTML5 Canvas的大小功能 [英] Resize function for HTML5 Canvas
问题描述
我设法组合一个动态调整大小的HTML5 Canvas,但它有问题。例如,它只是缩放高度,而不是宽度。我的画布宽度 900px
,高度 850px
。另一个问题是,它扩大了画布,超越了其定义的宽度和高度。
I managed to put together a dynamically resizing HTML5 Canvas but it has issues. For instance, it only scales the height, not the width too. My canvas has width of 900px
and height of 850px
. Another issue is that it enlarges the canvas too, way beyond it's defined width and height.
我做错了什么?
这里是我到目前为止尝试的:
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:
如果我尝试@havex说,改变属性像这样: canvas.width = width;
和 canvas.height = height;
而不是 canvas.style.width = width +'px';
和 canvas.style.height = height +'px' code>我得到的是一个可调整大小的盒子,但不是动画。请参阅图片:
If I try what @havex said, changing the attributes like so: canvas.width = width;
and canvas.height = height;
instead of canvas.style.width = width+'px';
and canvas.style.height = height+'px';
what I get is a resizable box BUT NOT the animation. See picture for reference :
推荐答案
我不能解释为什么发生,因为它是在早上4:30我还没有睡觉,但可以更改这些设置,并且应该可以正常工作(可以删除边框):
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):
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; }
这篇关于调整HTML5 Canvas的大小功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!