The Canvas Pixel Manipulation API

The Canvas Pixel Manipulation API gives us the ability to “get,” “put,” and “change” individual pixels, utilizing what is known as the CanvasPixelArray interface. ImageData is the base object type for this manipulation, and an instance of this object is created with the createImageData() function call. Let’s start there.

The createImageData() function sets aside a portion of memory to store an individual pixel’s worth of data based on the following three constructors:

imagedata = context.createImageData(sw, sh)

The sw and sh parameters represent the width and height values for the ImageData object. For example, imagedata=createImageData(100,100) would create a 100×100 area of memory in which to store pixel data.

imagedata = context.createImageData(imagedata)

The imagedata parameter represents a separate instance of ImageData. This constructor creates a new ImageData object with the same width and height as the parameter ImageData.

imagedata = context.createImageData()

This constructor returns a blank ImageData instance.

ImageData attributes

An ImageData object contains three attributes:

ImageData.height

This returns the height in pixels of the ImageData instance.

ImageData.width

This returns the width in pixels of the ImageData instance.

ImageData.data

This returns a single-dimensional array of pixels representing the image data. Image data is stored with 32-bit color information for each pixel, meaning that every fourth number in this data array starts a new ...

Get HTML5 Canvas, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.