Draw into a canvas, read a rectangle of its pixels, edit the returned RGBA values, and write the result back. The 2D context’s image-data reader gives you a snapshot rather than a live view, so changes appear only after you paint the modified data. This canvas pixel-reading method makes it possible to inspect color and alpha one pixel at a time.
Canvas GetImageData in a Working Example
Save this complete file as pixels.html and open it in a browser. It draws a blue rectangle, reads a smaller area, turns the red component of each pixel in that area up, and writes the modified area back. The result is a magenta rectangle inside the blue one, and the console reports the first pixel before and after the edit.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Canvas pixels</title>
</head>
<body>
<canvas id="picture" width="240" height="140"></canvas>
<script>
const canvas = document.querySelector("#picture");
const ctx = canvas.getContext("2d");
ctx.fillStyle = "rgb(0, 80, 200)";
ctx.fillRect(0, 0, canvas.width, canvas.height);
const x = 40, y = 30, width = 100, height = 60;
const image = ctx.getImageData(x, y, width, height);
const pixels = image.data;
console.log("Before:", Array.from(pixels.slice(0, 4)));
for (let i = 0; i < pixels.length; i += 4) {
pixels[i] = 255; // red; leave green, blue, and alpha alone
}
console.log("After:", Array.from(pixels.slice(0, 4)));
ctx.putImageData(image, x, y);
</script>
</body>
</html>
For this canvas getImageData returns an ImageData object with width, height, and data. The data is a one-dimensional array of components, ordered red, green, blue, and alpha for each pixel. In this default format it is a Uint8ClampedArray, with values from 0 to 255. The example reads 100 by 60 pixels, so the array contains 24,000 component values.
The drawing is generated locally by the script, so the example does not depend on an external image. Open DevTools and expand the two console arrays to compare the first pixel. The exact observed values can be affected by browser privacy settings or color handling, but the intended change is to raise red while leaving the other channels alone.
Locate a pixel in the rectangle
The arguments to getImageData are the rectangle’s left and top coordinates followed by its width and height. The canvas bitmap starts at (0, 0) in the upper-left corner, with x increasing to the right and y increasing downward. In the example, the selected region begins at (40, 30) and covers x coordinates 40 through 139 and y coordinates 30 through 89.
Once you retrieve image data, coordinates within the returned rectangle start again at (0, 0). For a local pixel at (px, py), the red component is at 4 * (py * image.width + px). Green, blue, and alpha follow at offsets one, two, and three. To inspect local pixel (2, 1), calculate 4 * (1 * 100 + 2), or 408; its four values occupy indexes 408 through 411.
A canvas getImageData operation uses the canvas bitmap’s coordinate system and is not affected by the current transformation matrix. CSS can display the canvas at a different size from its width and height attributes. If you use a mouse position from the page, convert it from the displayed rectangle to bitmap coordinates before reading a pixel. Otherwise the point you inspect can be offset or scaled relative to the pointer.
Interpret color and transparency
In the default eight-bit format, 0 represents the lowest channel value and 255 the highest. Red, green, and blue together describe the color. Alpha represents opacity: 0 is transparent and 255 is opaque; intermediate values are partially transparent. The example changes only red, so it preserves the existing opacity and the other two channels.
Reading image data from the canvas can reveal pixels that look similar against one background but have different alpha values. A partly transparent red pixel over white will look different over black. If you use pixel values for a calculation, decide whether the calculation concerns the stored channels or the color as composited over a particular background.
The returned data is a copy. Changing pixels[i] changes the ImageData object, not the visible canvas. putImageData(image, x, y) places that data at the chosen bitmap position. Like the read operation, this write is unaffected by the current transformation matrix. To compare original and edited versions, save a separate copy before modifying the array or draw the result into a second canvas.
Choose a safe region and workload
A request with zero width or height throws IndexSizeError. A rectangle extending beyond the canvas returns transparent black for the out-of-bounds portion; it does not automatically shrink to the visible area. Validate dimensions and clamp the region if your algorithm should operate only on existing canvas pixels. This is especially important for selections made by dragging near an edge.
Calling getImageData for a large region repeatedly can be expensive. Read only the region needed, process its components in one loop, and write it back once. If an effect runs on every animation frame, measure its cost in DevTools with realistic canvas dimensions before increasing the resolution. For a frequently read canvas, consider the context’s willReadFrequently option and test its performance in the browsers you support.
Load external images with permission
When you obtain image data from a canvas, the browser must be able to verify the origin of every source drawn into it. Drawing a cross-origin image without CORS approval taints the canvas. The image may still appear on screen, but subsequent pixel reads throw a SecurityError; exporting the canvas is restricted too.
For an image hosted on another origin, set image.crossOrigin = "anonymous" before setting image.src, and have the image server return an Access-Control-Allow-Origin header permitting the page’s origin. Wait for the image to load before drawing it. If the server does not grant access, the CORS-enabled image request can fail to load. Use an authorized same-origin source or obtain the server owner’s permission and configuration; JavaScript alone cannot grant access to someone else’s response.
The most likely failure after adding a remote picture is a SecurityError at the pixel-reading call. In DevTools, inspect the image request and its response headers, confirm that the CORS mode was set before the URL, and check that the allowed origin matches the page. Reload the image and draw it onto a fresh canvas after correcting the configuration, then repeat the read.
