Dragging-and-dropping shapes

In this recipe, we'll tackle the holy grail of event listeners—drag-and-drop. Without the Events class or some other lightweight JavaScript library, drag-and-drop operations can be quite cumbersome to develop. We can use the Events class to attach a mouseover, mousedown, mousemove, mouseup, and mouseout event listener to the rectangle to handle different phases of the drag-and-drop operation.

Dragging-and-dropping shapes

How to do it...

Follow these steps to drag-and-drop a rectangle:

  1. Link to the Events class:
    <script src="events.js">
    </script>
  2. Define the writeMessage() function which writes out a message:
    <script> function writeMessage(context, message){ ...

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.