我最近一直在使用canvas并且今天开始使用setInterval来定期刷新/动画。 我很惊讶地看到这对cpu来说是多么重要并且减慢了传送速度。在网上看例子我确信我的做法有问题。然后,我最大限度地简化了我想要做的事情(不是使用图像而是使用矩形,不使用太多的对象等),但仍然遇到了同样的问题。
我试图在两个矩形的顶部获得一个白色闪光(12fps)......所以没有什么比这更复杂了......
这是我的代码。
function Canvas(name){
this.ctx=document.getElementById(name).getContext('2d');
this.canvas=this.ctx.canvas;
this.width=this.canvas.width;
this.height=this.canvas.height;
this.layers=new Array();
this.draw = function() {
this.canvas.width = this.canvas.width;
this.ctx.beginPath();
this.ctx.rect(0,0,this.width,this.height);
this.ctx.closePath();
this.ctx.fillStyle="#eaeaea";
this.ctx.fill();
this.ctx.beginPath();
this.ctx.rect(250,50,300,250);
this.ctx.closePath();
this.ctx.fillStyle="#ff0000";
this.ctx.fill();
intensity=Math.random();
this.flash(intensity);
};
this.flash = function(intensity) {
this.ctx.globalAlpha = intensity;
this.ctx.beginPath();
this.ctx.rect(0,0,this.width,this.height);
this.ctx.closePath();
this.ctx.fillStyle="#fff";
this.ctx.fill();
this.ctx.globalAlpha = 1;
setInterval(this.draw.bind(this),1000);
};
function initCanvas(){
mycanvas=new Canvas('myCanvas');
mycanvas.draw();
}
$(document).ready(function() {
initCanvas();
});
找到解决方案:
答案 0 :(得分:2)
关闭您打开的所有路径:
this.draw = function() {
this.canvas.width = this.canvas.width;
this.ctx.beginPath();
this.ctx.rect(0,0,this.width,this.height);
this.ctx.closePath(); //Closing
this.ctx.fillStyle="#eaeaea";
this.ctx.fill();
this.ctx.beginPath();
this.ctx.rect(250,50,300,250);
this.ctx.closePath(); //Closing
this.ctx.fillStyle="#ff0000";
this.ctx.fill();
this.flash(40);
};
this.flash = function(intensity) {
this.ctx.globalAlpha = intensity;
this.ctx.beginPath();
this.ctx.rect(0,0,this.width,this.height);
this.ctx.closePath(); //Closing
this.ctx.fillStyle="#fff";
this.ctx.fill();
this.ctx.globalAlpha = 1;
setInterval(this.draw.bind(this),1000);
};
答案 1 :(得分:2)
由于您在setInterval
函数中继续使用flash
,因此内存泄漏严重。让我们看一下事件的顺序
draw
的间隔draw
要解决此问题,请在setTimeout
中使用flash
。因此,它会在一秒钟后调用draw
,调用flash
,然后在一秒钟内再次调用draw
。此外,1000毫秒不会给你12fps。 1000/12将。
另外,使用ctx.closePath();
关闭您使用beginPath()
您也从未使用Canvas
关闭}
功能。
这是demo
答案 2 :(得分:0)
我不知道这是否相关,但我发现自己处于类似情况,想要给出更好的答案。
使用requestAnimationFrame(yourLoop)
,特别是对于游戏,因为它更快,性能更好。
http://www.paulirish.com/2011/requestanimationframe-for-smart-animating/