Falcon80 Logo
Putting image data on to the canvas

If you have a pixel object containing colour and alpha (transparency) information, you can draw it anywhere on the canvas using the putImageData() method. The method takes in three parameters at the least:

putImageData(imagedata object,x,y);

where:

  • imagedata object is an array containing pixel information. This can be either created using the createImageData() or obtained as a return value from getImageData().
  • x and y are the coordinates where the pixel data has to be drawn

putImageData() method can take the following additional, optional parameters:

putImageData(imagedata object, x, y, dirtyX, dirtyY, dirtyWidth, dirtyHeight)

where:

  • x,y = The starting point of the dirty rectangle in the CSS bitmap
  • length = length of the dirty rectangle
  • breath = breath of the dirty rectangle

If you provide the optional parameters, then the putImageData() method will take only those pixels present inside the dirty rectangle and draw them on the canvas.

However, as of Gecko 1.9.1, the optional parameters remain unimplemented.

Notes:
1. If the canvas has images loaded from the hard disk and you try to access pixel information using the getImageData() method, it will not work and will show a security violation "NS_ERROR_DOM_SECURITY_ERR". This is because DOM will not allow accessing pixel data to be accessed if the underlying image is from a different domain. When the image comes from the hard disk, DOM does not know that the image is from the same domain and hence throws the error. To test your code without running into this error, run a local web server like apache,  or test your code from the server itself.

2. The getImageData() and putImageData() are expensive operations. So wherever possible, find ways to get around using them.

HTML Code
<html>
<head>
  <script type="application/javascript">
function init() {
var canvas = document.getElementById("canvas");
if (canvas.getContext)
{
var ctx = canvas.getContext("2d");

//Let's draw an image
var flower = new Image();
flower.src = "flower.png";
ctx.drawImage(flower,10,10);

//Read a rectangular area of pixels from the image
var imagedata = ctx.getImageData(20,10,40,30);

//Put the pixels back on canvas at location (150,10)
ctx.putImageData(imagedata,150,10); }
}

  </script>
<title> HTML5 Canvas - Pixel Manipulation </title>
</head>
<body onload="init();">
<canvas id="canvas" width="900" height="500"></canvas><br>
</body>
</html>

Try Code