使用一圈或两圈索引像素 [英] index a pixel using one-loop or two-loops
问题描述
我看到一些用户在[Image Data]数组中使用以下两种方法对像素进行索引:
I saw some user index a pixel in [Image Data] array, with the following two methods:
for(var i = 0; i < imageData.length; i+=4) {
data[i] = r;
data[i+1] = g;
data[i+2] = b;
data[i+3] = a;
}
或使用此方法。
for(var x = 0; w < canvas.width; x++) {
for(var y = 0; h < canvas.height; y++) {
var index = (x + y*canvas.width)*4;
}
}
所以,我想知道的是两者之间没有任何区别。另外,如果两者相同,则最快。
So, I want to know is there any difference between the two. Also, if the both are same, then which is fastest.
推荐答案
这完全取决于您的需求:
It all depends of your needs :
•如果需要线性遍历所有像素,只需执行以下操作:
• If you need to iterate through all pixel linearly, just do :
var pixelCount=data.length, i=0;
while (pixelCount--) {
data[i++] = r;
data[i++] = g;
data[i++] = b;
data[i++] = a;
}
•如果迭代所有像素,但需要(x,y)进行计算的每个点的数量:
• If you iterate though all pixels, but need the (x,y) of each points to perform some computations do:
var index=0, canvasWidth = canvas.width, canvasHeight = canvas.height ;
for(var y = 0; h < canvasHeight; y++) {
for(var x = 0; w < canvasWidth ; x++) {
data[index++] = /* depends on x, y */;
data[index++] = /* depends on x, y */;
data[index++] = /* depends on x, y */;
data[index++] = /* depends on x, y */;
}
}
(缓存canvas.width / height尤其重要以避免在循环内访问DOM)。
(it's especially important to cache canvas.width/height to avoid DOM access within a loop).
•如果您遍历数据中的矩形,那么就无法避免计算索引,可以通过使用移位来加快索引速度:
• If you iterate through a rectangle within the data, then you can't avoid computing the index, which you can speed up a bit by using bit shifting :
var startX = ?? , startY = ???, endX = ???, endY = ??? ;
var canvasWidth = canvas.width;
var index=0;
for(var y = startY; y <= endY; y++) {
for(var x = startX; x <= endX ; x++) {
index = ( y * canvasWidth + x ) << 2 ;
data[index] = ... ;
data[index+1] = ... ;
data[index+2] = ... ;
data[index+3] = ... ;
}
}
这篇关于使用一圈或两圈索引像素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!