HTML and CSS Reference
In the previous code listing, I wait until the image has loaded
before trying to copy it to the canvas. I draw it in to the can-
vas and immediately read out the pixel data to make my invert
adjustment to the pixels.
In the for loop, I'm using i += 4 , which ensures I'm iterating
over each pixel and not the pixel channels. By setting the pixel
bit to 255 minus the current value, I get an inverted colour.
Finally, I put the pixels variable back in to the canvas after
making my changes using putImageData , passing in the
CanvasPixelArray object and the x/y start point.
FIGURE 5.17 If you were to x-ray
Bruce and Remy, you'd see they
look just as strange.
NOTE The canvas element contains an internal origin-clean fl ag that's set
to true by default. This fl ag will fl ip to false if an image or video is used
whose origin does not match that of the document that owns the canvas. The
same goes for using a canvas as an image source if it already has the origin-
clean fl ag set to false. If the fl ag is false, it means that you won't be able to use
the getImageData or toDataURL methods. This remains the case even if you
change the size of your canvas or draw on the canvas after the fl ag is set to false.
Saving to fi le
Yo u ' v e m a d e t h e n e x t b e s t t h i n g s i n c e s l i c e d b r e a d ? W a n t t o
save your beautiful drawing to your desktop? You want to export
it in multiple formats? No problem. Canvas has you covered.
The canvas element (not the 2D context) supports exporting the
current state of the canvas to a data URL.