createImageData() Method - Javascript Canvas Reference

Javascript examples for Canvas Reference:createImageData


The createImageData() method creates a new, blank ImageData object whose pixel values are transparent black by default.

The pixel in the ImageData object are represented by the RGBA values:

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

For example, transparent black indicates: (0, 0, 0, 0).

The color/alpha information is stored in an array called ImageData object, whose length is

To create a new ImageData object with the specified dimensions in pixels:

var imgData = context.createImageData(width, height);

To create a new ImageData object with the same dimensions as the object specified by anotherImageData without copying copy the image data:

var imgData = context.createImageData(anotherImageData);

Parameter Values

Parameter Description
width The width of the new ImageData object, in pixels
heightThe height of the new ImageData object, in pixels
imageData anotherImageData object


The following code shows how to create a 200*200 pixels ImageData object where every pixel is red, and put it onto the canvas:

Demo Code

ResultView the demo in separate window

<!DOCTYPE html>

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


var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var imgData = ctx.createImageData(200, 200);

var i;//from   www. j a  va 2 s .com
for (i = 0; i <; i += 4) {[i+0] = 255;[i+1] = 0;[i+2] = 0;[i+3] = 255;

ctx.putImageData(imgData, 10, 10);



Related Tutorials