- Feature #10: Path-Based Graphics and the Nonzero Winding Rule
- Feature #9: Hit Detection
- Feature #8: canvas Is an HTML Element
- Feature #7: Temporary Drawing
- Feature #6: Offscreen Canvases
- Feature #5: Transforming the Coordinate System
- Feature #4: Image Manipulation
- Feature #3: Drawing Images and More with drawImage()
- Feature #2: The Clipping Region
- Feature #1: New Functionality in the 2D API
- Conclusion
Feature #2: The Clipping Region
One simple feature—the clipping region—lets you implement all sorts of interesting graphics effects. The application shown in Figure 9 implements a magnifying glass that the user can drag.
Figure 9 The magnifying glass uses the HTML5 Canvas clipping region.
As the user drags the mouse, the application uses drawImage() to draw the pixels contained within the smallest rectangle surrounding the magnifying glass lens back into the canvas, scaled at the current scale.
That call to drawImage() takes place after the application sets the clipping region with the 2D API's clip() method. Because the clipping region is specified with a circle representing the magnifying glass lens, the call to drawImage() only affects the area within the clipping region:
context.beginPath(); context.arc(magnifyingGlassX, magnifyingGlassY, magnifyingGlassRadius, 0, Math.PI*2, false); context.clip(); context.drawImage(canvas, magnifyRectangle.x, magnifyRectangle.y, magnifyRectangle.width, magnifyRectangle.height, magnifyRectangle.x + magnifyRectangle.width/2 - scaledMagnifyRectangle.width/2, magnifyRectangle.y + magnifyRectangle.height/2 - scaledMagnifyRectangle.height/2, scaledMagnifyRectangle.width, scaledMagnifyRectangle.height);
The clipping region, which has countless uses in addition those with magnifying glasses, is the Swiss Army knife of the 2D API.