The ImageData object
The imageData
object acts as a container/store for pixel information.
The
ImageData
object has width, height and data
properties. The data
property is a single dimension array that contains
red, blue, green and alpha values. All of the
values (including the alpha value) go from 0-255. By default each pixel in
the ImageData
object is transparent black
- so all of the values in the data
array will be 0.
After you have updated the values in the ImageData
object you can put the
changes back onto the canvas
with the
putImageData function
The ImageData
object has three properties - width, height and data.
Arguments to the function
- The width of the
ImageData
object - The height of the
ImageData
object
Note that the created objects data
array will have
four elements for each pixel - red, green, blue and alpha values.
So the size of the array will be: width * height * 4
Alternatively, you can pass a pre-existing ImageData
and the
dimensions of that will be used (but not the pixel data):
- Existing
ImageData
object
An example
<script>
window.onload = function ()
{
var canvas = document.getElementById('cvs');
var context = canvas.getContext('2d');
// Creates an ImageData object that's 100x100 pixels in size
var imgData = context.createImageData(100, 100);
}
</script>
An example using an existing ImageData object
This example shows you that you can also use an existing
ImageData
object instead of width and height. This creates a new
ImageData
object with the same amount of pixels as the one that
you pass (though it doesn't copy the pixel information).
<script>
window.onload = function ()
{
var canvas = document.getElementById('cvs');
var context = canvas.getContext('2d');
// Creates an ImageData object that uses the existing imageData objects width and height
var imgData = context.createImageData(imageData);
}
</script>