HTML5 Canvas Reference - putImageData()








The putImageData() function copies the pixels from an ImageData instance to the canvas.

Browser compatibility

putImageData() Yes Yes Yes Yes Yes

JavaScript Syntax

There are two different constructors for this call:

context.putImageData  (imagedata,  dx,  dy)
context.putImageData  (imagedata,  dx,  dy  [, dirtyX,  dirtyY, dirtyWidth,  dirtyHeight ])

The first version paints the entire ImageData instance to the destinationX (dx) and destinationY (dy) locations.

The second version accepts the "dirty rectangle", which represents the area of the ImageData to paint to the canvas.





Parameter Values

Parameter Description
imgData ImageData object to copy back onto the canvas
x The x-coordinate, in pixels, of the ImageData object upper-left corner
y The y-coordinate, in pixels, of the ImageData object upper-left corner
dirtyX Optional. The x-coordinate in pixels, where to place the image on the canvas
dirtyY Optional. The y-coordinate value, in pixels, where to place the image on the canvas
dirtyWidth Optional. The image width to draw
dirtyHeight Optional. The image height to draw




Example

The following code copies the pixel data for a specified rectangle with getImageData(), and then put the image data back onto the canvas with putImageData():


<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="300" height="150"></canvas>
<script>
    var c = document.getElementById("myCanvas");
    var ctx = c.getContext("2d");
    ctx.fillStyle = "red";
    ctx.fillRect(10, 10, 50, 50);<!-- ww w. j  a  v  a 2  s.  co  m-->

    var imgData = ctx.getImageData(10, 10, 50, 50);
    ctx.putImageData(imgData, 20, 70);

</script>

</body>
</html>

The code above is rendered as follows:

Example 2

The following code creates random color and sets back to canvas.


<!DOCTYPE html>
<html>
<body>
<canvas id="myCanvas" width="30" height="15"></canvas>
<script>
    var canvas, context, width, height;
    canvas = document.getElementById("myCanvas");
    context = canvas.getContext('2d');
    width = canvas.width;
    height = canvas.height;
    var imageData = context.createImageData(width, height);
    (function loop() {<!--from  www. ja v  a 2  s. c o m-->
        for (var i = 0, n = imageData.data.length; i < n; i++) {
            imageData.data[i] = Math.floor(Math.random() * 255);
        }
        context.putImageData(imageData, 0, 0);
        requestAnimationFrame(loop);
    })();

</script>

</body>
</html>

The code above is rendered as follows: