简体   繁体   中英

How to stop an animation in canvas?

I have this code to start animation:

function anim()
{
    mouse_x=cursor_x-x;
    mouse_y=cursor_y-y;
    context.fillRect(0,0,w,h);
    for(var i=0;i<n;i++)
        {
        test=true;
        star_x_save=star[i][3];
        star_y_save=star[i][4];
        star[i][0]+=mouse_x>>4; if(star[i][0]>x<<1) {star[i][0]-=w<<1; test=false; }
        if(star[i][0]<-x<<1) { star[i][0]+=w<<1; test=false; }
        star[i][1]+=mouse_y>>4; if(star[i][1]>y<<1) { star[i][1]-=h<<1; test=false; }
        if(star[i][1]<-y<<1) { star[i][1]+=h<<1; test=false; }
        star[i][2]-=star_speed; if(star[i][2]>z) { star[i][2]-=z; test=false; }
        if(star[i][2]<0) { star[i][2]+=z; test=false; }
        star[i][3]=x+(star[i][0]/star[i][2])*star_ratio;
        star[i][4]=y+(star[i][1]/star[i][2])*star_ratio;
        if(star_x_save>0&&star_x_save<w&&star_y_save>0&&star_y_save<h&&test)
            {
            context.lineWidth=(1-star_color_ratio*star[i][2])*2;
            context.beginPath();
            context.moveTo(star_x_save,star_y_save);
            context.lineTo(star[i][3],star[i][4]);
            context.stroke();
            context.closePath();
            }
        }
    timeout=setTimeout('anim()',fps);
    }

I am not able to stop this animation. I don't want to pause, I just wanted to destroy the animation function, so that it does not slow the performance of my application.

$(document).ready(function() {
    $(".destroy").click(function() {
        context.destory;
    });
});

Here is the full code

To tell the garbage collector to free the context memory, just set its reference variable to null.

context=null;

Before setting the context to null, you must stop the animation which you can do like this:

Create a Boolean flag that indicates if any future animation should execute:

// allow anim to do its animations
var doAnim=true;

Then, in the animation loop, if the flag indicates "stop" you simply return without executing the animation code:

function anim(){
    if(!doAnim){context=null; return;}
    ...
}

To stop animating, just set the flag to "stop":

doAnim=false;

Then if you later want to restart animating, you just reset the flag and call anim to start animating.

var context=...
doAnim=true;
anim();

You can the redefine the function with function anim(){}; though I'm not sure why you need to do such a thing.

But based on your question, I gather you want to destroy the resulting image in the canvas. The only way to do that is to reset the canvas to its beginning or a previously save state. Like this:

Reset:

context.clearRect(0, 0, canvas.width, canvas.height);

Save and restore: http://www.tutorialspoint.com/html5/canvas_states.htm

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM