CanvasRenderingContext2D.getImageData()

The CanvasRenderingContext2D.getImageData() method of the Canvas 2D API returns an ImageData object representing the underlying pixel data for the area of the canvas denoted by the rectangle which starts at (sx, sy) and has an sw width and sh height.

Syntax

ImageData ctx.getImageData(sx, sy, sw, sh);

Parameters

sx
The x coordinate of the upper left corner of the rectangle from which the ImageData will be extracted.
sy
The y coordinate of the upper left corner of the rectangle from which the ImageData will be extracted.
sw
The width of the rectangle from which the ImageData will be extracted.
sh
The height of the rectangle from which the ImageData will be extracted.

Return value

An ImageData object containing the image data for the given rectangle of the canvas.

Errors thrown

IndexSizeError
Thrown if either of the width or height arguments are zero.

Examples

Using the getImageData method

This is just a simple code snippet which uses the getImageData method. For more information, see Pixel manipulation with canvas and the ImageData object.

HTML

<canvas id="canvas"></canvas>

JavaScript

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
ctx.rect(10, 10, 100, 100);
ctx.fill();

console.log(ctx.getImageData(50, 50, 100, 100));
// ImageData { width: 100, height: 100, data: Uint8ClampedArray[40000] }

Specifications

Specification Status Comment
WHATWG HTML Living Standard
The definition of 'CanvasRenderingContext2D.getImageData' in that specification.
Living Standard  

Browser compatibility

Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support (Yes) (Yes) [1] (Yes) (Yes) (Yes)
Feature Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
Basic support (Yes) (Yes) (Yes) [1] (Yes) (Yes) (Yes)

[1] Starting with (Firefox 5.0 / Thunderbird 5.0 / SeaMonkey 2.2), getImageData() now correctly accepts rectangles that extend beyond the bounds of the canvas; pixels outside the canvas are returned as transparent black and now also returns at least one pixel's worth of image data if a rectangle smaller than one pixel is specified.

See also

Document Tags and Contributors

 Contributors to this page: fscholz, michaellaszlo
 Last updated by: fscholz,