The Mouse and the Canvas

Often times, the canvas seems like its own mysterious beast. It is not until you run into areas like events that aren’t specific to the canvas where you realize that all of this is just a small part of this larger JavaScript enclosure. For the next few sections, you are going to be learning general JavaScript 101 stuff about events, so feel free to skip or gloss over the material if you are intimately familiar with dealing with mouse events.

Meet the Events

Our canvas element works with all the mouse events that your browser exposes:

  • click
  • dblclick
  • mouseover
  • mouseout
  • mouseenter
  • mouseleave
  • mousedown
  • mouseup
  • mousemove
  • contextmenu
  • mousewheel and DOMMouseScroll

What these events do should be somewhat easy to figure out given their name, so I won’t bore you with details about that. Let’s just move on to the next section where we learn how to listen to them.

Listening to and Handling Mouse Events

To listen for these events on your canvas element, use the addEventListener method and specify the event you are listening for and the event handler to call when that event is overheard:

Get hands-on with 1200+ tech skills courses.