Hit Detection

A canvas is a single bitmap, meaning the browser does not natively track the individual shapes that you have drawn. To make these shapes interactive, use isPointInPath() and isPointInStroke() to determine if a coordinate (such as a mouse click) falls within a specific shape.

Hit Detection Methods

The 2D rendering context includes two methods to check whether a point lies within the current path:

Method Description
isPointInPath(x, y) Returns true if the point (x, y) is inside the area of the current path.
isPointInStroke(x, y) Returns true if the point (x, y) is on the outline of the current path.

How it Works

To implement hit detection, follow these steps:

  1. Define the shape's path using commands such as rect(), arc(), or lineTo().
  2. Use isPointInPath(x, y) to check if the user's mouse coordinates fall within that path.
  3. Respond to the user interaction.

Hit Detection Example

The following example defines a rectangle's path and then checks if the user's mouse click falls within that path:

View Output

Managing Multiple Shapes

If you have many shapes and want to track interactions for each, you must recreate each shape's path every time you want to test a coordinate. For more complex projects, it is common to store object data in an array and redraw or check them as needed.

We've now covered all the main features of the HTML canvas to get you started. Let's move on to the summary for a final recap of what we've learned.