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.
This method is not affected by the canvas's transformation matrix. If the specified rectangle extends outside the bounds of the canvas, the pixels outside the canvas are transparent black in the returned ImageData
object.
Note: Image data can be painted onto a canvas using the putImageData()
method.
You can find more information about getImageData()
and general manipulation of canvas contents in Pixel manipulation with canvas.
ctx.getImageData(sx, sy, sw, sh);
sx
ImageData
will be extracted.sy
ImageData
will be extracted.sw
ImageData
will be extracted. Positive values are to the right, and negative to the left.sh
ImageData
will be extracted. Positive values are down, and negative are up.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)
.
IndexSizeError
sw
or sh
are zero.SecurityError
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.This example draws a rectangle, and then uses getImageData()
to grab a portion of the canvas.
<canvas id="canvas"></canvas>
The object retrieved by getImageData()
has a width of 200 and a height of 100, for a total of 20,000 pixels. Of those pixels, most are either transparent or taken from off the canvas; only 5,000 of them are opaque black (the color of the drawn rectangle).
const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); ctx.rect(10, 10, 100, 100); ctx.fill(); let imageData = ctx.getImageData(60, 60, 200, 100); ctx.putImageData(imageData, 150, 10);
Specification | Status | Comment |
---|---|---|
HTML Living Standard The definition of 'CanvasRenderingContext2D.getImageData' in that specification. | Living Standard |
Desktop | ||||||
---|---|---|---|---|---|---|
Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | |
Basic support | Yes | 12 | Yes
|
Yes | Yes | Yes |
Mobile | |||||||
---|---|---|---|---|---|---|---|
Android webview | Chrome for Android | Edge Mobile | Firefox for Android | Opera for Android | iOS Safari | Samsung Internet | |
Basic support | Yes | Yes | Yes | Yes
|
Yes | Yes | Yes |
CanvasRenderingContext2D
ImageData
objectCanvasRenderingContext2D.putImageData()
© 2005–2018 Mozilla Developer Network and individual contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/getImageData