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. This method is not affected by the canvas transformation matrix.
Pixels outside of the canvas area are present as transparent black values in the returned ImageData.
ImageData ctx.getImageData(sx, sy, sw, sh);
sx
sy
sw
sh
An ImageData
object containing the image data for the given rectangle of the canvas.
IndexSizeError
getImageData
methodThis 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); ctx.fill(); console.log(ctx.getImageData(50, 50, 100, 100)); // ImageData { width: 100, height: 100, data: Uint8ClampedArray[40000] }
Specification | Status | Comment |
---|---|---|
HTML Living Standard The definition of 'CanvasRenderingContext2D.getImageData' in that specification. | Living Standard |
Feature | Chrome | Edge | Firefox (Gecko) | Internet Explorer | Opera | Safari |
---|---|---|---|---|---|---|
Basic support | (Yes) | (Yes) | (Yes) [1] | (Yes) | (Yes) | (Yes) |
Feature | Android | Chrome for Android | Edge | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
---|---|---|---|---|---|---|---|
Basic support | (Yes) | (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.
CanvasRenderingContext2D
.ImageData
© 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