Tag Archives: canvas

Mouse Clicks for HTML5 Cavas Entities via Paths

The canvas element in HTML5 is exciting because it really opens the doors to games, drawing, and animation. This is especially exciting as browsers hardware accelerate canvas and improve its performance. What isn’t so exciting though is that you do have to do a lot more for yourself.

So if you draw something into the canvas, you don’t get to attach event listeners on the objects you create within the canvas, just on the canvas itself. This means that you have to build your own event system. This isn’t that difficult if you organize your entities you’re drawing and rely on isPointInPath to do the searching for you.

Overview

When you use path methods, like arc, bezierCurveTo, or lineTo, the 2D context keeps track of things really nicely for you. After you add your path, you can ask the context whether or not a point is within the area of said path via the isPointInPath method.

The way to find the object is to render each entity in reverse order, draw the path, and then check to see isPointInPath. The reason to go in reverse order is because the most visible, unobstructed object is at the last index in the rendering order.

Paths are great because they are fast, but they are pretty plain. What you if you want to draw images? Well there’s no rule that you can only use one canvas. This means that you can use one canvas to draw your main stage with images, and then use the light-weight paths to draw the hit detection area.

The demo will draw the earth and the moon and will print a the name of the selected planet.

Continue reading