CanvasRenderingContext2D: putImageData() method
The
CanvasRenderingContext2D.putImageData()
method of the Canvas 2D API paints data from the given
ImageData
object
onto the canvas. If a dirty rectangle is provided, only the pixels from that rectangle
are painted. This method is not affected by the canvas transformation matrix.
Note:
Image data can be retrieved from a canvas using the
getImageData()
method.
You can find more information about
putImageData()
and general
manipulation of canvas contents in the article
Pixel manipulation with canvas
.
Syntax
js
putImageData(imageData, dx, dy)
putImageData(imageData, dx, dy, dirtyX, dirtyY, dirtyWidth, dirtyHeight)
Parameters
-
imageData -
dirtyXOptional
Horizontal position (x coordinate) of the top-left corner from which the image data
will be extracted. Defaults to
-
dirtyYOptional
Vertical position (y coordinate) of the top-left corner from which the image data
will be extracted. Defaults to
-
dirtyWidthOptional -
dirtyHeightOptional
An
ImageData
object containing the array of pixel values.
0
.
0
.
Width of the rectangle to be painted. Defaults to the width of the image data.
Height of the rectangle to be painted. Defaults to the height of the image data.
Return value
None (
undefined
).
Exceptions
-
NotSupportedErrorDOMException -
InvalidStateErrorDOMException
Thrown if any of the arguments is infinite.
Thrown if the
ImageData
object's data has been detached.
Examples
Understanding putImageData
To understand what this algorithm does under the hood, here is an implementation on top
of
CanvasRenderingContext2D.fillRect()
.
html
<canvas id="canvas"></canvas>
JavaScript
js
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
function putImageData(
ctx,
imageData,
dirtyX,
dirtyY,
dirtyWidth,
dirtyHeight,
const data = imageData.data;
const height = imageData.height;
const width = imageData.width;
dirtyX = dirtyX || 0;
dirtyY = dirtyY || 0;
dirtyWidth = dirtyWidth !== undefined ? dirtyWidth : width;
dirtyHeight = dirtyHeight !== undefined ? dirtyHeight : height;
const limitBottom = dirtyY + dirtyHeight;
const limitRight = dirtyX + dirtyWidth;
for (let y = dirtyY; y < limitBottom; y++) {
for (let x = dirtyX; x < limitRight; x++) {
const pos = y * width + x;
ctx.fillStyle = `rgba(${data[pos * 4 + 0]}, ${data[pos * 4 + 1]}, ${
data[pos * 4 + 2]
}, ${data[pos * 4 + 3] / 255})`;
ctx.fillRect(x + dx, y + dy, 1, 1);
// Draw content onto the canvas
ctx.fillRect(0, 0, 100, 100);
// Create an ImageData object from it
const imagedata = ctx.getImageData(0, 0, 100, 100);
// use the putImageData function that illustrates how putImageData works
putImageData(ctx, imagedata, 150, 0, 50, 50, 25, 25);
Result