Easy Tutorial
❮ Obj Location Met Win Matchmedia ❯

HTML canvas createImageData() Method

Canvas Object

Example

Create a 100*100 pixel ImageData object where each pixel is red, and then place it on the canvas:

JavaScript:


Browser Support

Internet Explorer 9, Firefox, Opera, Chrome, and Safari support the createImageData() method.

Note: Internet Explorer 8 and earlier versions do not support the <canvas> element.


Definition and Usage

The createImageData() method creates a new, blank ImageData object. The default pixel value for the new object is transparent black.

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

R - Red (0-255)

Therefore, transparent black represents (0,0,0,0).

The color/alpha information is stored in an array, and since the array contains four pieces of information for each pixel, the size of the array is four times the size of the ImageData object: widthheight4. (There is a simpler way to get the array size, which is to use ImageDataObject.data.length)

The array containing the color/alpha information is stored in the data property of the ImageData object.

Tip: After manipulating the color/alpha information in the array, you can use the putImageData() method to copy the image data back onto the canvas.

Example:

Syntax to change the first pixel in the ImageData object to red:

Syntax to change the second pixel in the ImageData object to green:


JavaScript Syntax

There are two versions of the createImageData() method:

  1. Create a new ImageData object with the specified dimensions (in pixels):

| JavaScript Syntax: | var imgData = context.createImageData(width, height); | | --- | --- |

  1. Create a new ImageData object with the same dimensions as another specified ImageData object (without copying the image data):

| JavaScript Syntax: | var imgData = context.createImageData(imageData); | | --- | --- |

Parameter Values

Parameter Description
width The width of the ImageData object, in pixels.
height The height of the ImageData object, in pixels.
imageData Another ImageData object.

Canvas Object

❮ Obj Location Met Win Matchmedia ❯