简短的回答:您可能没有使用 CSS 选择器正确定位 canvas 元素。
长“答案”:我认为有几点需要注意:
- 更改标签的
height
orwidth
属性canvas
将完全清除它(即删除任何绘制到它的东西,将其重置为空白状态)。(虽然显然,这在某些浏览器中不会发生。)
- 对于
<canvas>
元素,height
or属性与andwidth
的 CSS 属性有独特的关系,我在这里描述:https ://stackoverflow.com/a/19079320/1937302height
width
- 对
height
orwidth
属性的更改不会被“过渡”/动画化
- 对 CSS属性
height
或width
属性的更改将被“过渡”/动画化
我在这里演示了一些:
http://jsfiddle.net/BYossarian/WWtGZ/3/
HTML:
<canvas id="canvas1" height="50" width="100"></canvas>
CSS:
canvas {
border: 1px solid black;
transition: all 1s ease;
height: 50px;
}
JS:
var canvas = document.getElementById('canvas1'),
ctx = canvas.getContext('2d');
ctx.fillStyle = "red";
ctx.fillRect(10, 10, 30, 30);
// changing width attribute clears canvas element (in most broswers)
// changing width attribute isn't animated by CSS transition
setTimeout(function () {
canvas.width = "200";
}, 2000);
// changing CSS rule for width is animated, although if no CSS rule for width already exists, then a width of 0px is taken as the starting point
setTimeout(function () {
ctx.fillStyle = "red";
ctx.fillRect(10, 10, 30, 30);
canvas.style.width = "100px";
}, 4000);