javascript 遍历 HTML5 画布时获取 X 和 Y 像素坐标 getImageData
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13660723/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get X and Y pixel coordinates when iterating over HTML5 canvas getImageData
提问by jcvandan
I am iterating over some image data pulled from a canvas
like so:
我正在迭代一些从canvas
像这样提取的图像数据:
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?
如何计算我所在的当前 X 和 Y 像素坐标?
采纳答案by bill automata
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.
将线性位置除以宽度。那是你的 Y 坐标。将该 Y 坐标乘以宽度,然后从线性位置减去该值。结果是 X 坐标。
Also note, you will have to divide the linear position by 4 since it is RGBA.
另请注意,您必须将线性位置除以 4,因为它是 RGBA。
回答by user11153
Corrected and tested version of code:
更正和测试的代码版本:
var x = (i / 4) % this.el.width;
var y = Math.floor((i / 4) / this.el.width);