Chapter 12. DrawSVG and Draggable

Draggable

Dragging objects around your screen on the web is one of those things that seems like it would be pretty easy to implement—until you try to do it from scratch. There’s a lot to account for, with touch input, mouse events, viewports, scroll behavior, friction, and believable physics. There are more failure conditions than you would probably initially consider. Thankfully, GreenSock’s Draggable is a really powerful plug-in and works perfectly on SVG as well as HTML elements.

Draggable is device-enabled for touchscreens, uses requestAnimationFrame(), and is GPU-accelerated. Draggable works on its own but is more powerful when coupled with the ThrowPropsPlugin, which creates really beautiful physics-like motion.

One of the best things about Draggable is its simplicity. This is all it takes to make a box realistically draggable:

 Draggable.create(".box", {type:"x,y", edgeResistance:0.65,
  bounds:"#container", throwProps:true});

You may notice in the preceding code that we’ve defined some boundaries with bounds. bounds is pretty flexible: you can define containing units or pixel parameters. Something like "#container" (as in the preceding example) or section would work, but you could also say {top:10, left:10, width:800, height:600} in an object to restrict the movement.

You can also have it lock movement along the horizontal or vertical axis if you like by setting lockAxis:true, which will work in both directions.

There are lots of callbacks/event ...

Get SVG Animations 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.