如何计算画布中的 X 和 Y 坐标
how to calculate the x and y co-ordinates in a canvas
我试图通过从getImageData获得的数据来确定x和y坐标。 这是我的代码示例:
var img = ctx.getImageData(0, 0, c.width, c.height);
var pix = [],
coords = [];
for (var i = 0; i < img.data.length; i+=4) {
if (img.data[i]!== 0){
pix.push(i);
}
}
for (var j in pix) {
//wrong co-ordinate
var y = Math.floor(pix[j]/c.width);
//don't know how to determine x position
var x = 0;
coords.push({
x:x,
y:y
});
}
主要的计算块是:
if (img.data[i] !== 0) {
// Please look up in the explaination part for this.
j = i / 4;
quo = Math.floor(j / cols);
pix.push({
x: quo,
y: j - (quo * cols)
});
}
如果这是我们假设的像素数组:
0 1 2 3
4 5 6 7
那么相应的图像数据将是:
0,1,2,3 4,5,6,7 8,9,10,11 12,13,14,15
16,17,18,19 20,21,22,23 24,25,26,27 28,29,30,31
首先我们迭代i += 4
,跳块到块得到0,4,8,...当我们执行j = i / 4;
时,我们将此图像数据转换为原始像素数组,例如。如果 i = 20,则在像素数组中表示 5。
现在,一旦我们得到像素数组,对于x坐标:
quo = Math.floor(j / cols);
将其除以列,它给出了它所属的行。
在查找列索引时:我们执行以下操作:
j - (quo * cols);
这意味着,(quo * cols)给出了该行上的第一个元素。减去它给我,从该行的第一个元素中有多少元素之后,我会得到它。这只不过是列索引。在这种情况下,以及我们的 x 坐标。
请检查以下代码:
var canvas = document.createElement('canvas'),
context = canvas.getContext('2d'),
rows = 512,
cols = 512,
img,
pix = [],
co_ords = [],
quo;
// sets the height and width for the canvas.
canvas.width = cols;
canvas.height = rows;
// append the canvas to the document.
document.body.appendChild(canvas);
// draw a simple rectangle at (10,10)
context.fillStyle = "red";
context.fillRect(10, 10, 50, 50);
// extract the imageData for the canvas.
img = context.getImageData(0, 0, rows, cols);
// iterate for every 4th data, as there is a (R,G,B,A) set mapped for every pixel.
for (i = 0; i < img.data.length; i += 4) {
// check if its a valid pixel(non-empty)
if (img.data[i] !== 0) {
// Please look up in the explaination part for this.
j = i / 4;
quo = Math.floor(j / cols);
pix.push({
x: quo,
y: j - (quo * cols)
});
}
}
console.log(pix);
给定像素地址作为索引并知道图像宽度。
x = (Math.floor(index/4)) % width;
y = Math.floor(index/(4 * width));
相关文章:
- 如何在d3.js中返回路径的y坐标
- 如何在JS Leatflet绘图插件中获取圆的坐标
- 如何在OpenLayers中获取动态绘制的多边形的坐标
- 获取用户位置并将坐标保存在数据库中
- 无法获取表单's面板的x和y坐标,并在加载时从cookie中设置它们
- 将鼠标坐标保存在阵列中
- Javascript 地理位置:将坐标存储在数组中
- 高股票图表中每个 yAxis 的 X 坐标
- 如何在 JavaScript 中计算 SVG 路径的椭圆路径坐标
- 将地理位置坐标放入数组中
- 谷歌地图在angularjs中懒惰加载动态地理坐标更新
- 将坐标传递到HTML页面以在新窗口中打开谷歌街景
- 使用谷歌地图和Angular JS.正在尝试将坐标存储在变量中
- JS坐标->PHP脚本-如何在PHP中保留变量
- 如何在谷歌地图javascript中在地图上拖动标记(可拖动方向)时显示更新的坐标
- 在javascript中从数据库下载坐标时,谷歌地图未显示
- Algorithm/Formula创建一条线/条,该线/条遵循坐标列表中的一组规范
- 如何在Javascript的onclick函数中放置x和y坐标对象中的动画
- Regex:从一串坐标列表中找出第一个坐标
- 如何在平行坐标图中使用不同方向的轴标签