单击循环停止动画(问题)

时间:2014-09-04 03:57:29

标签: javascript animation

当用户点击动画的最后一帧时,我遇到的问题与动画冻结有关。我做了JSFiddle。动画在最后一帧时单击,它将冻结。当用户点击时,我尝试过阻止输入的东西。

if(active === false){
   active = true;
}

但无济于事。这可能是一件简单的事情我只是毫无头绪。

3 个答案:

答案 0 :(得分:1)

试试这个 -

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var activeIMG;
var active = false;
var frame = 7;
window.images = {
    c0: new Image(),
    c1: new Image(),
    c2: new Image(),
    c3: new Image(),
    c4: new Image(),
    c5: new Image(),
    c6: new Image()
};
images.c0.src = 'http://i.imgur.com/Tw3iDG6.png'; //Normal
images.c1.src = 'http://i.imgur.com/nFS1YYw.png'; //Start
images.c2.src = 'http://i.imgur.com/f8BYubj.png'; //Boom
images.c3.src = 'http://i.imgur.com/96N0hLn.png'; //Boom Smoke
images.c4.src = 'http://i.imgur.com/1iACNo8.png'; //Thick Smoke
images.c5.src = 'http://i.imgur.com/eZxuXtC.png'; //Lighter Smoke
images.c6.src = 'http://i.imgur.com/ooZJYa9.png'; //Rounding Smoke
activeIMG = images.c0;

$('body').mousedown(function (event) {
    var chords = ("X: " + event.pageX + "Y: " + event.pageY);
    if (frame > 6) {
        active = true;
        frame = 0;
    }
});
setInterval(function change() {
    if (active) {
        activeIMG = window.images["c" + frame++];
        //console.log(activeIMG)
        active= frame <= 6;
    } else {
        activeIMG = window.images["c0"];
    }       
}, 150);

    function draw() {
        ctx.clearRect(0, 0, canvas.width, canvas.height)
        ctx.drawImage(activeIMG, 0, 0);

        requestAnimationFrame(draw);
    }
    draw();

这是演示http://jsfiddle.net/vikrant47/vh9mgwk8/2/

答案 1 :(得分:0)

您在点击第6帧后立即将active设置为false,因此现在可以“重新启动”,您希望在第6帧被绘制时设置它/或第7帧(重复帧1)开始。

在案例6中设置断点并逐步执行。

答案 2 :(得分:0)

这就是我实现这一目标的方式,看看我在您的代码中做了一些更改:

var test = function(event){
    var chords = ("X: " + event.pageX + "Y: " + event.pageY);
    //alert(chords);
    active = true;
};

$('body').bind('click',test);//binding click event

$('body').unbind('click');//unbinding it when animation is going on for preventing unwanted click
/* made some changes in case 6 also, binding click event once more and set frame to 0 */
case 6:
     activeIMG = images.c6;
     active = false;
     frame=0;//most important to make frame from start again
     $('body').bind('click',test);//binding again
     break;

DEMO