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.


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


The x coordinate of the upper left corner of the rectangle from which the ImageData will be extracted.
The y coordinate of the upper left corner of the rectangle from which the ImageData will be extracted.
The width of the rectangle from which the ImageData will be extracted.
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

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


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.


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


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

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


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


© 2016 Mozilla Contributors
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.