如何在画布中复制动画

时间:2013-02-27 11:09:25

标签: javascript canvas

我有一个正在绘制的半圆形动画,我基本上想要复制它,然后将副本向下移动60px然后向新的一个添加延迟一秒,这样它就会画出一个“B”

HTML

<canvas id="thecanvas"></canvas>

脚本

var can = document.getElementById('thecanvas');
ctx = can.getContext('2d');
can.width = window.innerWidth;
can.height = window.innerHeight;

window.drawCircle = function (x, y) {
    segments = 90, /* how many segments will be drawn in the space */
    currentSegment = 0,
    toRadians = function (deg) {
        return (Math.PI / 180) * deg;
    },
    getTick = function (num) {
        var tick = toRadians(180) / segments; /*360=full, 180=semi, 90=quarter... */
        return tick * num;
    },
    segment = function (end) {
        end = end || getTick(currentSegment);
        ctx.clearRect(0, 0, can.width, can.height);
        ctx.beginPath();
        ctx.arc(x, y, 60, (1.5 * Math.PI), end + (1.5 * Math.PI), false);
        ctx.stroke();
        ctx.closePath();
    };

    ctx.lineWidth = 5;
    ctx.strokeStyle = 'rgba(0,0,0,0.5)';

    setTimeout(function render() {
        segment(getTick(currentSegment));
        currentSegment += 1;
        if (currentSegment < segments) {
            setTimeout(render, 5);
        } else {
            currentTick = 0;
        }
    }, 250);
};
drawCircle(100, 100); 

这是一个小提琴http://jsfiddle.net/zhirkovski/bJqdN/

1 个答案:

答案 0 :(得分:0)

首先,您可以将setTimeout函数放在drawCircle方法之外。

然后你至少有两个选择:

  1. 创建一个“endDraw”事件,该事件将在1次绘制结束时调度。处理此事件时,只需再次调用drawCircle方法。要实现这一点,当然你需要一个main方法来调用第一个drawCircle。

  2. 为了提供更好的解决方案,您可以描述呼叫的工作流程。即描述要调用的方法列表以及每个方法的起始帧:

    var workflow = [{method:"drawCircle", frame:0, x:100, y:100},      //the first half circle at the frame 0, x=100, y=100
                    {method:"drawCircle", frame:1000, x:100, y:190}];  //the second half circle starting at frame 1000, x=100, y=190
    

    您的主计时器将被配置为使用此阵列来了解要执行的操作