ParticleSpawner.prototype.metabilize = function(ctx) {
var imageData = this._tempCtx.getImageData(0,0,900,675),
pix = imageData.data;
this._tempCtx.putImageData(imageData,0,0);
for (var i = 0, n = pix.length; i <n; i += 4) {
if(pix[i+3]<210){
pix[i+3] = 0;
}
}
//ctx.clearRect(0,0,900,675);
//ctx.drawImage(this._tempCanvas,0,0);
ctx.putImageData(imageData, 0, 0);
}
我在我的代码中使用了另一个循环,并通过使用以下链接描述的技术 http://www.fatagnus.com/unrolling-your-loop-for-better-performance-in-javascript/ 来提高其性能,但是在这个循环上使用相同的技术实际上会降低性能(也许我做错了?)
我还研究了Web Workers以查看是否可以分割负载(因为代码针对每个像素单独运行),但是我在此链接中找到的示例http://blogs.msdn.com/b/eternalcoding/archive/2012/09/20/using-web-workers-to-improve-performance-of-image-manipulation.aspx 实际上会使速度更慢。
还有什么其他方法可以尝试吗? 有没有办法从循环中删除分支? 另一种展开它的方法? 还是这已经是我所能做到的最好的了?
编辑:
这是周围部分代码:
ParticleSpawner.prototype.drawParticles = function(ctx) {
this._tempCtx.clearRect(0,0,900,675);
var iterations = Math.floor(this._particles.getNumChildren() / 8);
var leftover = this._particles.getNumChildren() % 8;
var i = 0;
if(leftover > 0) {
do {
this.process(i++);
} while(--leftover > 0);
}
do {
this.process(i++);
this.process(i++);
this.process(i++);
this.process(i++);
this.process(i++);
this.process(i++);
this.process(i++);
this.process(i++);
} while(--iterations > 0);
this.metabilize(ctx);
}
以及处理方法:
ParticleSpawner.prototype.process = function(i) {
if(!this._particles.getChildAt(i)) return;
var bx = this._particles.getChildAt(i).x;
var by = this._particles.getChildAt(i).y;
if(bx > 910 || bx < -10 || by > 685) {
this._particles.getChildAt(i).destroy();
return;
}
//this._tempCtx.drawImage(this._level._queue.getResult("particleGradient"),bx-20,by-20);
var grad = this._tempCtx.createRadialGradient(bx,by,1,bx,by,20);
this._tempCtx.beginPath();
var color = this._particles.getChildAt(i).color;
var c = "rgba("+color.r+","+color.g+","+color.b+",";
grad.addColorStop(0, c+'1.0)');
grad.addColorStop(0.6, c+'0.5)');
grad.addColorStop(1, c+'0)');
this._tempCtx.fillStyle = grad;
this._tempCtx.arc(bx, by, 20, 0, Math.PI*2);
this._tempCtx.fill();
};
可以看到,我尝试使用图像代替渐变形状,但性能更差,我还尝试使用ctx.drawImage代替putImageData,但它会失去alpha通道并且不会更快。我无法想到其他方法来实现所需的效果。当前代码在Google Chrome上运行完美,但Safari和Firefox非常慢。我还有什么尝试的余地吗?我应该放弃这些浏览器吗?