getImageData method

Returns an ICanvasImageData object that represents the pixel data for the specified rectangle on a canvas. Use the data property to get a CanvasPixelArray to manipulate individual pixel data.

HTML Canvas 2D Context, Section 13Internet Explorer 9

Syntax

var retval = CanvasRenderingContext2D.getImageData(sx, sy, sw, sh);

Parameters

sx [in]

Type: number

The x-coordinate, in pixels, of the upper-left corner of the rectangle in relation to the coordinates of the canvas.

sy [in]

Type: number

The y-coordinate, in pixels, of the upper-left corner of the rectangle in relation to the coordinates of the canvas.

sw [in]

Type: number

The width, in pixels, of the rectangle in relation to the coordinates of the canvas.

sh [in]

Type: number

The height, in pixels, of the rectangle in relation to the coordinates of the canvas.

Return value

Type: ICanvasImageData

A CanvasImageData object with pixel information from the canvas within the specified coordinates.

Standards information

Remarks

If the rectangle contains pixels outside the canvas, they are returned as transparent black.

Examples

The following code example draws some shapes on one canvas and copies the data to a second canvas. See the example in action.


<!DOCTYPE html> 
<html>
<head>
  <title>Get and Put image data sample</title>
  <style type="text/css">
     #MyCanvas {        
       border:1px solid red;
     }
     
     #YourCanvas {
       border:1px solid blue;
     }
  </style>
</head>
<body>      
   Click the image to copy canvas to the other canvas
   <div>
     <canvas id="MyCanvas" width="400" height="400" >This browser or document mode doesn't support canvas</canvas>
     <canvas id="YourCanvas" width="400" height="400">This browser or document mode doesn't support canvas</canvas>
   </div>

   <script>
     // get first canvas and draw image
     var canvas = document.getElementById("MyCanvas");
     if (canvas.getContext) {
       var ctx = canvas.getContext("2d");
       ctx.beginPath();
       ctx.rect(5, 5, 300, 250);
       ctx.stroke();
       ctx.arc(150, 150, 100, 0, Math.PI, false);
       ctx.stroke();
     }

     canvas.addEventListener("click", function (){
       // get both canvases, and copy image
       var canvas2 = document.getElementById("YourCanvas");
       if (canvas.getContext) {
         var ctx = canvas.getContext("2d");                // Get the context on the first canvas.
         var imageStuff = ctx.getImageData(0, 0, canvas.width, canvas.height);    // Get image data from the first canvas.
       }
       if (canvas2.getContext) {
         var ctx2 = canvas2.getContext("2d");                // Get the context on the second canvas.
         ctx2.putImageData(imageStuff, 0, 0);                  // Put image data on the second canvas.
       }
     },false);
     
  </script>
  </body>
</html> 


See also

CanvasRenderingContext2D
CanvasPixelArray
putImageData
data

 

 

Show:
© 2014 Microsoft