问题
I am iterating over some image data pulled from a canvas
like so:
var imageData = this.context.getImageData(0, 0, this.el.width, this.el.height);
var data = imageData.data;
for (var i = data.length; i >= 0; i -= 4) {
if (data[i + 3] > 0) {
data[i] = this.colour.R;
data[i + 1] = this.colour.G;
data[i + 2] = this.colour.B;
}
}
How do I calculate the current X and Y pixel coordinates that I am at?
回答1:
A Simple Arithmetic Sequence:
Divide the linear position by the width. That's your Y-coordinate. Multiply that Y-coordinate by the width, and subtract that value from the linear position. The result is the X coordinate.
Also note, you will have to divide the linear position by 4 since it is RGBA.
回答2:
Corrected and tested version of code:
var x = (i / 4) % this.el.width;
var y = Math.floor((i / 4) / this.el.width);
来源:https://stackoverflow.com/questions/13660723/get-x-and-y-pixel-coordinates-when-iterating-over-html5-canvas-getimagedata