Der Hauptblock der Berechnung ist:
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)
});
}
Wenn dies das Pixel-Array gehen wir davon aus:
0 1 2 3
4 5 6 7
Dann entsprechenden imagedata würde 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
Zuerst iterieren wir i += 4
, springender Block zum Blockieren, erhalten 0,4,8, ... Wenn wir j = i/4;
tun, wandeln wir diese Bilddaten zu unserem ursprünglichen Pixel-Array um, z. wenn i = 20, in Pixelanordnung seine repräsentieren 5.
Nun, sobald wir das Pixel-Array, für bekommen x-Koordinate:
quo = Math.floor(j/cols);
dividieren sie durch die Spalten, und es gibt die Zeile gehört.
Während der Suche nach dem Spaltenindex: wir tun:
j - (quo * cols);
Das bedeutet, (quo * cols) gibt das erste Element in dieser Reihe. Subtrahieren gibt mir, nach wie vielen Elementen aus dem ersten Element in dieser Zeile, werde ich es bekommen. Dies ist nichts als der Spaltenindex. und in diesem Fall unsere x-Koordinate.
Überprüfen Sie bitte den folgenden 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);
Koordinaten von was? – Rayon
Angenommen, das Array pix enthält den Wert 16500. Ich möchte wissen, wo sich das Pixel in der Zeichenfläche in x- und y-Koordinaten befindet. – decatron
Welches Pixel? Alle Pixel? Versuchen Sie, eine Matrix für jedes Pixel zu erstellen? Wie wäre es dann mit "i ... j"? – Rayon