遍历 HTML5 画布 getImageData 时获取 X 和 Y 像素坐标

2022-01-17 00:00:00 javascript html5-canvas

我正在迭代从 canvas 中提取的一些图像数据,如下所示:

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

如何计算我当前所在的 X 和 Y 像素坐标?

How do I calculate the current X and Y pixel coordinates that I am at?

推荐答案

一个简单的算术序列:

将线性位置除以宽度.那是你的Y坐标.将该 Y 坐标乘以宽度,然后从线性位置中减去该值.结果是 X 坐标.

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.

另外请注意,您必须将线性位置除以 4,因为它是 RGBA.

Also note, you will have to divide the linear position by 4 since it is RGBA.

相关文章