HTML and CSS Reference
In-Depth Information
drawing.data[i+2] = 255 - drawing.data[i+2];
// invert blue
}
Now that the data has been modified, we simply write it back to the
canvas
element,
using the
putImageData(...)
command:
mycontext.putImageData(drawing, 0, 0); // put the image data back at (0,0)
Discussion
As we discussed in
Recipe 9.1
, the image that is rendered visible on the page is the
bitmap data rendering of the paths and styles (or vectors) that you defined while draw-
ing your image.
Fortunately, the
canvas
element allows us to access and modify some or all of the pixel
color data in the element. This means that any manner of sophisticated bitmap trans-
formations can be accomplished. In addition to applying color transformations, as we
did here, you could apply algorithms to blur the image, pixelate it, zoom it, etc. Those
various algorithms are beyond the scope of this chapter (and this topic), but the process
would always be the same as that outlined in this recipe: first get the bitmap image data
array, then process the individual color component (red, green, blue, alpha) entries for
each pixel, and then write some or all of that data back to your
canvas
element.
If you write an external image to a
canvas
element that comes from a
different domain than the page's domain, the
canvas
is marked as
“unclean” (meaning it's not abiding by the same-origin security policy),
and thus you are not able to call
getImageData(...)
to retrieve that data.
You can always write to the
canvas
element, but you can only read data
from it if
all
the data in the
canvas
originated from the page's domain.
See Also
This recipe only briefly touched on basic ways to manipulate the colors in your
can
vas
images and drawings. For much more complex effects that you can apply to your
canvas
element, check out PaintbrushJS:
http://mezzoblue.github.com/PaintbrushJS/
demo/
.
9.7 Working with Geometric Transformations
Problem
You want to apply some transformations to your drawing commands, such as scaling,
rotation, skewing, etc.