[英]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.