如何在前一个动画结束后开始动画?

时间:2015-03-27 17:56:16

标签: javascript jquery animation canvas html5-canvas

我有一个动画功能,可同时播放所有动画。这不是我想要的,我希望在前一个动画结束后播放每个动画。我该怎么做?

canvas = document.getElementById("test");
ctx = canvas.getContext("2d");

function animateLines(name, x1, y1, x2, y2, stroke, width, duration){
    var count = 0;
    var ms = 10;
    duration = duration * ms;
    var counter;

    function countNumbers(){
        ctx.beginPath();
        ctx.moveTo(x1, y1);

        count += 1;
        if(x2 > x1){
            ctx.lineTo((x1 + count), y2);
        }

        else if(y2 > y1){
            ctx.lineTo(x1, (y1 + count));
        }

        if((x1 < x2) && (count == x2)){
            clearInterval(counter);
        }

        else if((y1 < y2) && (count == y2)){
            clearInterval(counter);
        }
        ctx.lineWidth = width;
        ctx.strokeStyle = stroke;
        ctx.stroke();
    }

    $("#pause").on("click", function(){
        clearInterval(counter);
    })

    $("#play").on("click", function(){
        counter = setInterval(countNumbers, duration);
    })
}

animateLines("Line", 0, 100, 100, 100, "white", 5, 3);
animateLines("Line2", 150, 250, 350, 250, "red", 5, 2);
animateLines("Line3", 100, 0, 100, 300, "blue", 5, 1);

所以基本上,我想点击播放并开始Line的动画。完成后,启动Line2,完成后,Line3启动。

1 个答案:

答案 0 :(得分:0)

此代码必须适合您。对不起,我没有保留你的代码风格并在一个对象下写下所有内容,但我希望你能理解那里发生的事情。

canvas = document.getElementById("test");
ctx = canvas.getContext("2d");
var anim={
    currentStep:0,
    steps:[
        {name:"Line", x1:0, y1:100, x2:100, y2:100, stroke:"yellow", width:5, duration:3},
        {name:"Line2", x1:150, y1:250, x2:350, y2:250, stroke:"red", width:5, duration:2},
        {name:"Line3", x1:100, y1:0, x2:100, y2:300, stroke:"blue", width:5, duration:1}
        ],
    count:0,
    ms:10,
    counter:0,
    draw: function(){
        var cur=anim.steps[anim.currentStep];
        ctx.beginPath(); ctx.moveTo(cur.x1, cur.y1);
        anim.count += 1;
        if(cur.x2 > cur.x1){ctx.lineTo((cur.x1 + anim.count), cur.y2);}
        else if(cur.y2 > cur.y1){ctx.lineTo(cur.x1, (cur.y1 + anim.count));}
        if((cur.x1 < cur.x2) && (anim.count == cur.x2)){anim.changeStep();}
        else if((cur.y1 < cur.y2) && (anim.count == cur.y2)){anim.changeStep();}
        ctx.lineWidth = cur.width;
        ctx.strokeStyle = cur.stroke;
        ctx.stroke();
        },
    changeStep: function(){
        anim.currentStep++;
        anim.count=0;
        if(anim.currentStep==anim.steps.length){clearInterval(anim.counter); console.log('stopped');}
        }
    };
$("#pause").on("click", function(){clearInterval(anim.counter);});
$("#play").on("click", function(){anim.counter=setInterval(anim.draw, anim.steps[anim.currentStep].duration*anim.ms);});