2016-07-17 62 views
1

我試圖通過從getImageData獲得的數據確定x和y座標。下面是我的代碼的示例:如何計算畫布中的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 
    }); 
} 
+0

協調什麼? – Rayon

+0

假設如果數組pix包含一個值16500我想知道畫布中的像素在x和y方向上的位置 – decatron

+0

哪個像素?所有的像素?你是否想要創建每個像素的矩陣?那麼'我...... j'循環呢? – Rayon

回答

1

計算的主要塊是:

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 

然後相應的imageData將成爲:

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

這意味着,(現狀*的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);

+0

嘿@decatron,讓我知道如果這是你在找什麼。我將記錄並更新解釋。 – Ayan

+0

感謝您的代碼,它對我的​​工作非常好 – decatron

+1

請問您對計算的解釋? – decatron

1

鑑於像素地址作爲索引並知道圖像寬度。

x = (Math.floor(index/4)) % width; 
y = Math.floor(index/(4 * width)); 
+0

謝謝瞎子這個計算對我有好處:) – decatron