The CanvasRenderingContext2D method getImageData() of the Canvas 2D API returns an ImageData object representing the underlying pixel data for a specified portion of the canvas.

You can find more information about using getImageData() and manipulation of the contents of a canvas in general in the article Pixel manipulation with canvas.

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 rectangle of the canvas specified. The coordinates of the rectangle's top-left corner are (sx, sy), while the coordinates of the bottom corner are (sx + sw, sy + sh).

Exceptions

IndexSizeError
Thrown if either sw or sh are zero.
SecurityError
The canvas contains or may contain pixels which were loaded from an origin other than the one from which the document itself was loaded. To avoid SecurityError being thrown in this situation, configure CORS to allow the source image to be use in this way. See Allowing cross-origin use of images and canvas.

Usage notes

This method is not arffected by the canvas's transformation matrix. If the specified rectangle extends outside the bounds of the canvas, the pixels outside the canvas are black in the returned ImageData object.

Example

This example draws a rectangle then uses getImageData() to grab a portion of the cvanvas.

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
HTML Living Standard
The definition of 'CanvasRenderingContext2D.getImageData' in that specification.
Living Standard  

Browser compatibility

FeatureChromeEdgeFirefoxInternet ExplorerOperaSafari
Basic support Yes12

Yes

51

Yes Yes Yes
FeatureAndroid webviewChrome for AndroidEdge mobileFirefox for AndroidOpera AndroidiOS SafariSamsung Internet
Basic support Yes Yes Yes

Yes

51

Yes Yes Yes

1. 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: Sheppy, TimothyGu, fscholz, zbjornson, brttd, nmve, erikadoyle, michaellaszlo
Last updated by: Sheppy,