HTML and CSS Reference
In-Depth Information
This returns an object containing three properties: width , height , and data . The width and height
properties are the size of the image in pixels, and data is an array representing the image data. We will
look at this in more detail shortly.
To create a new, blank, ImageData object, specify the rectangle dimensions and call:
var imagedata = context.createImageData(width, height);
Alternatively, you can invoke this function with another ImageData object, e.g.
context.createImageData(anotherImageData) . This creates a new object with the same dimensions
as the argument. The pixels of the new object are set to transparent black, as this method does not copy
the image data.
When reading pixel data, any external asset rendered to the canvas—image or video—
is served from the same domain as the document running the script. If a cross-origin
image is drawn to the canvas, it is marked as dirty, and you will no longer be able to
read the pixels; instead, a security exception error is thrown to the debugging console.
This is in the HTML5 specification and is consistent with the same-origin security policy
used by most web browsers. Consequently, even testing some examples on your local
machine might be impossible. Unless your browser provides options to ignore this
security policy, you'll need to upload everything to a server and test it from there.
Accessing pixel components
The data property of an ImageData object returns a one-dimensional array containing the values of the
pixel component colors in RGBA order, specified as integers in the range 0 to 255. (Note that alpha is also
assigned a value in this range; not the 0.0 to 1.0 range used in the CSS-style color format.) The pixels are
ordered left to right, row by row, from top to bottom.
For example, here's an array representing the image data of a 2 × 2 square. Each of the four pixels is set
to full red:
var pixels = [ 255, 0, 0, 255, 255, 0, 0, 255,
255, 0, 0, 255, 255, 0, 0, 255];
The color components of the first pixel are marked in bold, and the array continues in groupings of four
elements—RGBA—for every pixel in the image. Each has its red and alpha channels set to full (255), and
its green and blue channels set to none (0).
You can access the values of any particular pixel by specifying an offset index for the array. Since each pixel is
represented by four elements, you can iterate over the image data, pixel by pixel, using the following:
for (var offset = 0, len = pixels.length; offset < len; offset += 4) {
var r = pixels[offset], //red
g = pixels[offset + 1], //green
b = pixels[offset + 2], //blue
a = pixels[offset + 3]; //alpha
}
Search WWH ::




Custom Search