Canvas 2D Web Apps/Draggable Objects

This chapter introduces draggable objects, i.e., images that can be dragged around with a mouse or a one-finger touch gesture. One notable feature of the presented approach is that any number of objects can be dragged simultaneously on a multi-touch device. Moreover, application programmers don't have to worry about the handling of multiple simultaneous touch events: the process function receives only events with a single pair of coordinates and processes only one object at a time.

The Example
The example of this chapter (which is available online; also as a downloadable version) shows two draggable objects: one cannot be dragged more than 100 pixels down; the second can be dragged only on a line between two points and snaps to one of the endpoints if it is no longer dragged. The following sections discuss how to set up these draggable objects. See the chapter on the framework for other parts.

The code creates one page with two draggable objects using three images (see the chapter on responsive buttons for a discussion of images):

The definition of the two global variables for the draggable objects is quite straightforward:

The process function of the page handles these two objects. The first one is processed by this code:

The process function of the draggable objects requires the event, coordinates of a rectangle, a text string, and three images similar to those of responsive buttons. Additionally, the constant  specifies that dragging with one finger should be possible. It returns  if it has processed the event. Our reaction here is to check whether the object has been translated (i.e. moved) more than 100 pixels down from its original position. In that case, the translation is set to those 100 pixels. Thus, the object cannot be dragged beyond that line.

The second draggable object is handled by this code:

Here, the translation in x direction is set to 0; i.e. the object cannot move horizontally. Furthermore, the translation in y direction is restricted to a range of 0 to 100 pixels. Lastly, if the dragging has stopped, the translation in y direction is set either to 0 or 100, i.e. it snaps to one of these points.

Of course, there are many more possibilities of reacting to the dragging of objects; for example, the detection of flick gestures.

Implementation of Draggable Objects
The implementation of draggable objects is actually more similar to the implementation of buttons than one might expect. First a constructor is defined and some methods to determine whether and how the object has been clicked:

Draggable objects have considerably more members than buttons because they have to keep track of various positions during the dragging.

The process function computes changes of these members depending on the state of the objects and of the current event: