繁体   English   中英

如何在画布上停止动画?

[英]How to stop an animation in canvas?

我有以下代码来启动动画:

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);
    }

我无法停止该动画。 我不想暂停,我只是想销毁动画功能,以免降低应用程序的性能。

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

这是完整的代码

要告诉垃圾收集器释放context内存,只需将其引用变量设置为null。

context=null;

在将上下文设置为null之前,必须停止动画,您可以像这样进行操作:

创建一个布尔型标志,指示是否将来应执行任何动画:

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

然后,在动画循环中,如果该标志指示“停止”,则仅返回而不执行动画代码:

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

要停止动画,只需将标志设置为“停止”即可:

doAnim=false;

然后,如果以后要重新启动动画,则只需重置标志并调用anim开始动画。

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

您可以使用anim(){}函数重新定义该函数; 尽管我不确定您为什么需要这样做。

但是根据您的问题,我认为您想销毁画布上的结果图像。 唯一的方法是将画布重置为其开始或先前的保存状态。 像这样:

重启:

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

保存和恢复: http : //www.tutorialspoint.com/html5/canvas_states.htm

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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