Skip to content
Advertisement

making each canvas line draggable and droppable

I am able to draw some lines on the canvas. I want to make each line draggable and droppable.

However, it is implemented by storing the positions of different lines in the array, how can I make each of them like an instance that is draggable and droppable? Or did I get it wrong?

You can check out the code here

var storedLines = []

http://jsfiddle.net/m1erickson/NnZ7a/

Thanks a lot!

Advertisement

Answer

Canvas draggables.

To make draggable lines you keep an array of endpoints and an array of lines as indexes to end points.

Then when the user clicks and drags near an end point or line you just update the endpoints by the amount the mouse has moved.

A point, a line, and some lists

First create a simple point structure

JavaScript

Then an list that will hold points, add points, and what ever else you may need.

JavaScript

You then create a points list from the list structure

JavaScript

The line is a set of point indexes

JavaScript

Finding the closest

To select a point from a mouse coordinate you need to find the closest point to the mouse.

JavaScript

The same for the line but that is not as simple. You need a function that finds the distance that a point is from a line segment.

JavaScript

With these function we should have extended the list object so will recreate them with the extensions.

JavaScript

Then the rest is implementing a mouse interface and a rendering function. You add draggable points and lines connecting them. If you click near a line or point you drag them. The snippet shows the rest.

User feedback is important

It is also important to show the correct user feedback. You need to set the cursor, tooltip (via canvas.style.cursor and canvas.title) and highlight objects that will be effected, so that the user knows what actions will happen and to what when they click and drag.

Also you should set the mouse events to the document rather than the canvas as this will capture the mouse drag allowing the user to drag outside the canvas while you still get the mouseup and move events.

Create and drag points and lines.

JavaScript
JavaScript
JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement