私は最近canvasで遊んでいて、今日からsetIntervalを使用して定期的に更新/アニメーション化する作業を開始しました。これがCPUにとってどのように重く、すべての動作が遅くなるかを見て驚いた。オンラインで例を見ると、私のやり方に何か問題があると確信しています。次に、やりたいことを最大限に単純化しました(画像ではなく長方形で遊んだり、オブジェクトを多用しすぎたりしないなど)が、それでも同じ問題が発生しました。
私は2つの長方形の上に白いフラッシュ(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();
});
見つかった解決策:
setIntervalの代わりにsetTimeoutを使用します。