Reputation: 7483
I need a way to find the coordinates of each pixel that have a specific color. I could loop through every pixel in the entire image and check if that matches, but that doesn't seem very efficient. Is there a better way?
Upvotes: 0
Views: 186
Reputation:
You will have to loop through the array as that is the only way to evaluate all the pixels in the canvas.
However, you can use 32-bit integer (typed) array instead of the standard 8-bit array - that will be many times faster:
var idata = ctx.getImageData(0, 0, ctx.canvas.width, ctx.canvas.height),
buffer32 = new Uint32Array(idata.data.buffer),
len = buffer32.length,
i = 0, x, y,
color = 0xffffffff; /// white color (ABGR format on little-endian systems)
for(; i < len; i++) {
if (buffer32[i] === color) {
/// convert i to x/y position here
x = i % idata.width;
y = (i / idata.height)|0;
}
}
Upvotes: 2