Baseline Widely available
Hinweis: Diese Funktion ist in Web Workers verfügbar.
Die readonly-Eigenschaft ImageData.data
gibt ein Uint8ClampedArray
oder ein Float16Array
zurück, das die Pixel-Daten des ImageData
-Objekts enthält. Die Daten werden als eindimensionales Array in der RGBA-Reihenfolge gespeichert, mit ganzzahligen Werten zwischen 0
und 255
(einschlieÃlich).
Der Typ hängt vom verwendeten ImageData.pixelFormat
ab:
Uint8ClampedArray
, wenn das pixelFormat
"rgba-unorm8"
ist.Float16Array
, wenn das pixelFormat
"rgba-float16"
ist.Dieses Beispiel erstellt ein ImageData
-Objekt, das 100 Pixel breit und 100 Pixel hoch ist, was insgesamt 10.000 Pixel ergibt. Das data
-Array speichert vier Werte für jedes Pixel, was 4 x 10.000 oder insgesamt 40.000 Werte ergibt.
let imageData = new ImageData(100, 100);
console.log(imageData.data); // Uint8ClampedArray[40000]
console.log(imageData.data.length); // 40000
Wenn das ImageData
-Objekt für Gleitpunkt-Pixel eingerichtet ist â zum Beispiel für Bilder mit hohem Dynamikbereich (HDR) â wird data
stattdessen ein Float16Array
sein.
let floatArray = new Float16Array(4 * 200 * 200);
let imageData = new ImageData(floatArray, 200, 200, {
pixelFormat: "rgba-float16",
});
console.log(imageData.data); // Float16Array
Füllen eines leeren ImageData-Objekts
Dieses Beispiel erstellt und füllt ein neues ImageData
-Objekt mit bunten Pixeln.
<canvas id="canvas"></canvas>
JavaScript
Da jedes Pixel aus vier Werten innerhalb des data
-Arrays besteht, iteriert die for
-Schleife in Vielfachen von vier. Die Werte, die mit jedem Pixel verbunden sind, sind R (rot), G (grün), B (blau) und A (alpha), in dieser Reihenfolge.
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
const imageData = ctx.createImageData(100, 100);
// Fill the array with RGBA values
for (let i = 0; i < imageData.data.length; i += 4) {
// Percentage in the x direction, times 255
let x = ((i % 400) / 400) * 255;
// Percentage in the y direction, times 255
let y = (Math.ceil(i / 400) / 100) * 255;
// Modify pixel data
imageData.data[i + 0] = x; // R value
imageData.data[i + 1] = y; // G value
imageData.data[i + 2] = 255 - x; // B value
imageData.data[i + 3] = 255; // A value
}
// Draw image data to the canvas
ctx.putImageData(imageData, 20, 20);
Ergebnis Weitere Beispiele
Für weitere Beispiele zur Verwendung von ImageData.data
, siehe Pixelmanipulation mit Canvas, CanvasRenderingContext2D.createImageData()
und CanvasRenderingContext2D.putImageData()
.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4