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 schreibgeschützte ImageData.data-Eigenschaft gibt ein Uint8ClampedArray zurück, das die Pixeldaten des ImageData-Objekts enthält. Die Daten werden als eindimensionales Array im RGBA-Format gespeichert, mit Ganzzahlen zwischen 0 und 255 (einschließlich).

Wert

Beispiele

Abrufen der Pixeldaten eines ImageData-Objekts

Dieses Beispiel erstellt ein ImageData-Objekt, das 100 Pixel breit und 100 Pixel hoch ist, insgesamt also 10.000 Pixel. Das data-Array speichert vier Werte für jedes Pixel, was insgesamt 4 x 10.000 oder 40.000 Werte ergibt.

js
let imageData = new ImageData(100, 100);
console.log(imageData.data); // Uint8ClampedArray[40000]
console.log(imageData.data.length); // 40000

Ausfü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 im data-Array besteht, iteriert die for-Schleife in Vielfachen von vier. Die Werte, die jedem Pixel zugeordnet 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-dev

Browser-Kompatibilität

Report problems with this compatibility data on GitHub
desktopmobileserver
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
Deno
data

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support

Siehe auch