如何计算画布中的 X 和 Y 坐标

how to calculate the x and y co-ordinates in a canvas

本文关键字:坐标 布中 何计算 计算      更新时间:2023-09-26

我试图通过从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));