Get X and Y pixel coordinates when iterating over

2019-02-02 09:34发布

问题:

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