Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Possible to drag an HTML dom element & drop onto an SVG dom element?

I'm currently using Raphaël JS (open to switching to jQuery SVG) and jQuery UI to try and make a prototype of a board game. It's somewhat similar to Risk in that the board is a map and you can (hopefully soon) drag pieces from one zone on the map to another (say from A to B) and drop them there. Once dropped, it would trigger a callback to do some work.

Right now I'm stuck trying to get the drag/drop functionality. I want to drag an html element (div) and drop it onto an SVG element. I'm not very familiar with SVG, but from what I understand there's issues to overcome in getting the HTML and SVG DOMs to work together.

I've got two versions and I'm trying to get jQuery UI to drag/drop to with either of them. One is using jQuery SVG with the svgdom plugin + jQuery UI and the other is just Raphaël + jQuery UI. Neither of them seems to be firing the drop event. As far as I know, the Raphaël version doesn't work because jQuery's dom manipulation can't interact with the SVG dom.

JS Fiddle jQuery SVG: http://jsfiddle.net/cqMUL/5/ (you'll have to scroll far down to see the SVG elements, my apologies).

The other possible solutions seem to be:
a) Using Raphaël with it's builtin drag and onDragOver functions, although then I'm using all SVG and I'm trying to use the HTML dom for the moving pieces because they will be images (div with background image). In addition, I'd probably have to implement drop myself.
b) Trying to use HTML5 drag & drop, although I'm not sure this would work either.

like image 320
MAP Avatar asked Oct 17 '11 01:10

MAP


2 Answers

This is an old question, but I'll give a shot at answering it anyway. The solution I came up with worked like this:

  1. Use JQueryUI to create the "draggable" functionality. It has a lot of convenient hooks.
  2. Attach mouseover and mouseout events to the SVG elements.
  3. Create a custom drag/drop manager.
  4. When you start a drag, register the element (or associated data) with the dragdrop manager.
  5. When you hover over a drop target, register that target with the dragdrop manager.
  6. Check your "drop" criteria on JQueryUI.draggable's "stop" event, and do the processing required there.

You can see an example of this in action (using D3 to generate the SVG) here: http://bl.ocks.org/thudfactor/6611441

like image 192
John Williams Avatar answered Sep 27 '22 16:09

John Williams


Indeed, SVG is difficult to manipulate. Here is an example you could base your programming on; just look at the source.

Alternatively, if ever you decide to abandon SVG, here are a couple of other ideas.

  1. You could make the pieces absolutely positioned <div>s with different z-indexes, then use jquery ui to move them.
  2. You could use Canvas and HTML5. Using this, you wouldn't need JQuery UI either.
like image 28
Choy Avatar answered Sep 27 '22 16:09

Choy