- 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 #9: Hit Detection
For many Canvas-based applications, it's crucial to determine whether a point lies within a particular path, and the 2D API makes that easy to do with the isPointInPath() method. For example, the application shown in Figure 2 lets you create polygons and drag them around.
Figure 2 Dragging polygons in an HTML5 Canvas.
The application in Figure 2 implements a mouse-down event handler and uses the 2D context's isPointInPath() method to detect a hit within one of the polygons:
canvas.onmousedown = function (e) { var loc = windowToCanvas(e.clientX, e.clientY); e.preventDefault(); // prevent cursor change if (editing) { polygons.forEach( function (polygon) { polygon.createPath(context); if (context.isPointInPath(loc.x, loc.y)) { startDragging(loc); dragging = polygon; draggingOffsetX = loc.x - polygon.x; draggingOffsetY = loc.y - polygon.y; return; } }); } else { startDragging(loc); dragging = true; } };
The isPointInPath() method is a simple but crucial element of the 2D API. In fact, hit detection is so important to Canvas-based applications that it has received a significant upgrade in the latest version of the Canvas specification.