画布是双缓冲的。您需要延迟动画的每个步骤,setTimeout()
以便让画布有机会绘制您的更改。更新:作为requestAnimationFrame
.setTimeout()
我为您创建了一个示例,该示例通过调用上下文方法并暂停来绘制矩形的每个段。我想我知道你正在寻找的特定动画,这不是它,但希望它能给你一个好的开始。
下面的代码和演示在这里:http: //jsfiddle.net/q8GcR/
function animateRoundRect(ctx, x, y, width, height, radius, delay) {
commands = [
['moveTo', x,y+radius],
['lineTo', x,y+height-radius],
['quadraticCurveTo', x,y+height,x+radius,y+height],
['lineTo', x+width-radius,y+height],
['quadraticCurveTo', x+width,y+height,x+width,y+height-radius],
['lineTo', x+width,y+radius],
['quadraticCurveTo', x+width,y,x+width-radius,y],
['lineTo', x+radius,y],
['quadraticCurveTo', x,y,x,y+radius]
];
function draw() {
var args = commands.shift();
var method = args.shift();
ctx[method].apply(ctx, args);
ctx.stroke();
if (commands.length) {
setTimeout(draw, delay);
}
}
ctx.beginPath();
draw();
}
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
ctx.lineWidth = 3;
ctx.strokeStyle = '#f00';
animateRoundRect(ctx, 20, 20, 250, 100, 10, 500);