decatron decatron - 4 months ago 10
Javascript Question

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

I'm trying to determine the x and y co-ordinates by the data obtained from getImageData. Here is a sample of my code:

var img = ctx.getImageData(0, 0, c.width, c.height);
var pix = [],
co_ords = [];
for (var i = 0; i < img.data.length; i+=4) {
if(img.data[i]!=0){
pix.push(i);
}
}

for (j in pix) {
//wrong co-ordinate
y = Math.floor(pix[j]/c.width);
//don't know how to determine x position
x = 0;
co_ords.push({
x:x,
y:y
});
}

Answer

The main block of calculation is:

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

If this is the pixel array we are assuming:

0 1 2 3
4 5 6 7

Then corresponding imageData would be:

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

Firstly we iterate i += 4, jumping block to block getting 0,4,8,... When we do j = i / 4; we convert this image data to our original pixel array, eg. if i = 20, in pixel array its representing 5.

Now once we get the pixel array, for x-coordinate:

quo = Math.floor(j / cols);

Divide it by the columns, and it gives the row it belongs.

While finding the column index: we do:

j - (quo * cols);

This means, (quo * cols) gives the first element on that row. Subtracting it gives me, after how many elements from the first element in that row, I will get it. This is nothing but the column index. and our x-coordinate in this case.

Please check the following code:

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