Home > Articles > Web Development > HTML/CSS

  • Print
  • + Share This
From the author of Feature #9: Hit Detection

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.

  • + Share This
  • 🔖 Save To Your Account