Guru
Guru

Reputation:

Drag and drop in mozilla canvas

I want to implement a drawing pane (similar but smaller version to what visio gives for flow charts) in mozilla canvas.

Is there any support for this?

I have used jQuery till now to create the rectangles and move them around. While this is easy here..creating lines (connections between objects) is a real pain. I am using some crude way to color pixel by pixel in javascript and it is neither looking good nor scalable and also I need to build a lot of functions to make the connections stick to a set of objects etc.

Does anyone know if the canvas and the functions available there will make my life easier.

Any pointers to what is a better solution in this case. (I am hoping it is not applet)

Thanks in advance.

Upvotes: 9

Views: 5541

Answers (3)

Sina
Sina

Reputation: 775

Either of these jQuery plugins are great for drawing panes:

jCanvas For drawing any simple and even complex shapes

sketch.js for drawing in general.

They are both responsive and compatible.

Upvotes: 0

treeno
treeno

Reputation: 2600

Yes you can use canvas for that. Drawing simple shapes and scaling them is pretty simple.

But if you need to edit the shapes after you have drawn them, you will have to invest some more work. Canvas draws in a so called "immediate mode", which means, that it does not know what you have painted right after you have painted it. It does not keep track of painted shapes. If you need that you will have to implement that on your own.

I have done this using the isPointInPath() function which can be used to test if a user clicks on a particular point. I keep track of my painted objects using the MVC-Pattern (Model-View-Controller), so that I can find out which Shape has been clicked on.

Another alternative might be fabrics.js which should be very close to what you need.

Upvotes: 1

hello512
hello512

Reputation: 379

Please follow this link : https://developer.mozilla.org/en-US/docs/Web/API/Canvas_API/Tutorial

LMK if it helps!

Following steps may help:
1. Create and add a canvas to the DOM :
var myCanvas = document.createElement('canvas'); document.body.appendChild(myCanvas);
2. Set the width-height of canvas :
myCanvas.width=200; myCanvas.height=200;
3. Get the context of the canvas and start drawing on it :
var gc = myCanvas.getContext('2d');
4. Code to draw rectangle :
gc.strokeRect(50,50,50,50);
5. After this, add mousehandlers(mousedown,mousemove,mouseup)/touchhandlers(touchdown,touchmove,touchup) on the canvas and handle the movement accordingly.

Upvotes: 0

Related Questions