ImageData: data-Eigenschaft

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.

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

Wert

Der Typ hängt vom verwendeten ImageData.pixelFormat ab:

Beispiele

Abrufen der Pixel-Daten eines ImageData-Objekts

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.

js
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.

js
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.

HTML

html
<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.

js
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

Spezifikationen

Specification
HTML
# dom-imagedata-data

Browser-Kompatibilität

Siehe auch