計算的主要塊是:
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);
協調什麼? – Rayon
假設如果數組pix包含一個值16500我想知道畫布中的像素在x和y方向上的位置 – decatron
哪個像素?所有的像素?你是否想要創建每個像素的矩陣?那麼'我...... j'循環呢? – Rayon