Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / JavaScript

ImageData.data — reading and modifying RGBA pixels

ImageData holds a rectangular area of pixels. Its ImageData.data property exposes a one-dimensional array of RGBA channels: its elements can be changed even though the property itself is read-only. Learn pixel indexing and the distinction between 8-bit and floating-point formats.

Version: ECMAScript and Web APIs; exact feature edition and browser support reviewed per entry; Node 24 in repository does not prove browser API support

Syntax

const imageData = new ImageData(width, height);
const pixels = imageData.data;
const i = 4 * (y * imageData.width + x);
pixels[i + 0] = red;
pixels[i + 1] = green;
pixels[i + 2] = blue;
pixels[i + 3] = alpha;

ImageData is a Web API interface, not part of ECMAScript itself. It represents a rectangular area of pixels; create it with new ImageData(width, height) or obtain it through a canvas 2D context's createImageData() or getImageData(). The constructor without an array creates transparent black pixels.

ImageData.data exposes channels in RGBA order: red, green, blue, and alpha. Pixels are stored row by row, starting at the top-left corner. The array contains 4 * width * height elements. For integer coordinates 0 <= x < width and 0 <= y < height, the red channel index is 4 * (y * width + x); subsequent channels have offsets 1, 2, 3.

The default "rgba-unorm8" format uses a Uint8ClampedArray with integer values from 0 to 255; alpha 0 means fully transparent and 255 fully opaque. The "rgba-float16" format uses a Float16Array, so do not apply the byte scale to it. Check support for that format and the experimental pixelFormat property separately in target browsers.

The data property is read-only, but the returned array's elements are not: modify imageData.data[i] rather than assigning a replacement array to imageData.data. Changing the buffer does not automatically update a canvas; use putImageData(imageData, 0, 0). Having Node 24 available does not establish support for this browser API.

Examples

const imageData = new ImageData(2, 1);
const pixels = imageData.data;
pixels.set([255, 0, 0, 255, 0, 255, 0, 255]);

const x = 1;
const y = 0;
const i = 4 * (y * imageData.width + x);
pixels[i + 2] = 255;

console.log(`${imageData.width}x${imageData.height}; ${pixels.length}`);
console.log(Array.from(pixels).join(','));

Result

2x1; 8
255,0,0,255,0,255,255,255

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources