HTML canvas putImageData() Method

Introduction

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

View in separate window

<!DOCTYPE html>
<html>
<body>

<canvas id="myCanvas" width="300" height="180" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>

<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.fillStyle = "red";
ctx.fillRect(10, 10, 50, 50);/*  w  w  w .j a  v  a  2  s  .com*/

function copy() {
  var imgData = ctx.getImageData(10, 10, 50, 50);
  ctx.putImageData(imgData, 10, 70);
}
</script>

<button onclick="copy()">Copy</button>

</body>
</html>

The putImageData() method puts the image data from ImageData object back onto the canvas.

context.putImageData(imgData, x, y, dirtyX, dirtyY, dirtyWidth, dirtyHeight);

Parameter Values

Parameter Description
imgData Set the ImageData object to put back onto the canvas
x The x-coordinate, in pixels, of the upper-left corner of on the canvas
y The y-coordinate, in pixels, of the upper-left corner of on the canvas
dirtyX Optional. The x-coordinate, in pixels, of the upper-left corner to start drawing the image. Default 0
dirtyY Optional. The y-coordinate, in pixels, of the upper-left corner to start drawing the image. Default 0
dirtyWidth Optional. The width to use when drawing the image. Default: the width of the extracted image
dirtyHeight Optional. The height to use when drawing the image. Default: the height of the extracted image



PreviousNext

Related