Get X and Y pixel coordinates when iterating over HTML5 canvas getImageData

只谈情不闲聊 提交于 2020-01-10 07:56:09

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!