Skip to content Skip to sidebar Skip to footer

Index A Pixel Using One-loop Or Two-loops

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+

Solution 1:

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;
}

• 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 */;
    }
 } 

(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] = ... ;
      }
   }

Solution 2:

Both of these methods will produce the same results. I assume that the index placement is the same in both images once they are calculated. The only thing that changes is the order that pixels are changed in.

For speed, the second one is likely to be slower. First of all, this is because of caching speed, programs can access data in similar array locations faster than continuously accessing locations across the array. Additionally, the compiler has to do a few multiplication operations and an addition in order to recalculate the index, instead of just an addition. For faster speed on the second one, try switching the x and y for loops, or multiply x by canvas.height instead of y by canvas.width.

Solution 3:

The previous answer work but I think I can provide a single loop answer.

Imagine we have to pick the pixels in a square image of 100x100:

const size = 100;
const pixels = size * size;

for( let index = 0; index < pixels; index++ ){

    const id = ~~index;
    const x = id % size;
    const y = ~~(id / size);

    console.log("x:", x, "y:", y);

}

Open your dev-tools to see the full console output.

Post a Comment for "Index A Pixel Using One-loop Or Two-loops"