Creating an Events class

Similar to Chapter 5, Bringing the Canvas to Life with Animation, where we created a custom class to handle animations, in this chapter we'll create a custom class to handle canvas events.

As canvas shapes are not accessible as objects (bummer!), there's nothing for us to attach event listeners to like we would with a div element as follows:

document.getElementById("foo").addEventListener("mouseup", function() {
  // do stuff
}, false);

So what can we do? If we follow the pattern of the canvas API, in which the beginning of a shape is defined with beginPath() , and the end of the shape is defined by closePath() , we can extend this idea one step further by introducing the concept of regions, which encapsulate multiple shapes. ...

Get HTML5 Canvas Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.