5

I have searched a lot, but I could not find a scenario which is relevant to my need. I want to drag and drop images from a toolbar to a canvas, not from a canvas to another canvas.

Please help me on this. Thanks in advance

CGG
  • 253
  • 1
  • 11
  • 22
dnWick
  • 393
  • 3
  • 14

1 Answers1

5

Demo: http://jsfiddle.net/m1erickson/2Us2S/

Use jquery-ui to create draggable elements.

$("#myToolbarImageElement").draggable();

Load these elements with data payloads which are key-value pairs.

In your case this might be an image object that you want drawn on the canvas.

$("#myToolbarImageElement").data("image",myImageObject);

Set your canvas as a drop zone:

$("#myCanvas").droppable({drop:myDropHandler});

When you drop the elements on canvas you can read the data (image) and drawImage that image to the canvas.

function myDropHandler(e,ui){
    var x = ui.offset.left - $("#myCanvas").offset.left;
    var y = ui.offset.top  - $("#myCanvas").offset.top;
    var image = ui.draggable.data("image");
    // draw on canvas
    drawImage(image,x,y);
}

Here's a nice tutorial on drag-drop elements with data payloads using jquery-ui:

http://www.elated.com/articles/drag-and-drop-with-jquery-your-essential-guide/

markE
  • 102,905
  • 11
  • 164
  • 176
  • Thanks a lot. Can you help me to make it more like a workflow , where i can connect these images with arrows, like you know those connecting points and also to change position of the dragged item on the canvas ? in this its kind of like static when dragged to the canvas. ? – dnWick Feb 09 '14 at 13:05
  • Here's a link on creating connectors between draggable canvas rectangles: http://stackoverflow.com/questions/18575006/connect-canvas-with-lines That should get you started. Good luck with your project! – markE Feb 09 '14 at 16:30
  • hi, i used the above example and i can do the drop but it happens only once, i need it to happen as many as the user drags the image and also i used the jquery ui clone property and once it dropped to the canvas i cannot drag them n the canvas.. can you help me on this? – dnWick Feb 10 '14 at 15:16
  • @markE How to make a version that works with a touch screen. I can't get that part to work. – Paul Meems Sep 30 '14 at 13:07
  • Touch screen drag & drop is a whole different question. You might ask a new question with the 'jquery-mobile' tag. – markE Sep 30 '14 at 14:58