HTML canvas getImageData() Method

Introduction

The code below 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  ww  .  j av  a  2s  . c  o m

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

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

</body>
</html>

The getImageData() method returns an ImageData object that copies the pixel data for a rectangle on a canvas.

For every pixel in an ImageData object there are four pieces of information, the RGBA values:

ItemValue
R The color red (from 0-255)
G The color green (from 0-255)
BThe color blue (from 0-255)
A The alpha channel (from 0-255; 0 is transparent and 255 is fully visible)

The color/alpha information is held in an array, and is stored in the data property of the ImageData object.

You can copy the image data back onto the canvas with the putImageData() method.




PreviousNext

Related