sirjay
sirjay

Reputation: 1766

Raphael.JS: How drag and drop image dom elements in raphael paper

I have html toolbox with set of images. I want to drag and drop them to raphael canvas. Using jquery ui or html5 I guess I can drag and drop, but how make that toolbox html elements (images) raphael objects when it is dropped?

I need function that pass html elem to raphael like this:

var r = Raphael(0, 0, 800, 800);

raiseMeWhenDropped(html_elem, e) {
    // create image on canvas area when dropped from toolbox
    r.image(html_elem.src, e.mouseXdropped, e.mouseYdropped, 30, 30);
}

Upvotes: 0

Views: 759

Answers (1)

Julien Grégoire
Julien Grégoire

Reputation: 17114

Simplest way would probably be to use HTML drag and drop and make your function the handler on drop event. You can add the drop event to the canvas element of your paper. Like this for example:

var r = Raphael(0, 60, 800, 800);
var canvas = r.canvas;
var dragImage = document.getElementById('test');

dragImage.addEventListener('dragstart', function (e) {
    dragEvent = e;
});

canvas.addEventListener('dragover', function (e) {
    e.preventDefault();
});

canvas.addEventListener('drop', function (e) {
    e.preventDefault();
    r.image(dragEvent.target.src, e.offsetX - dragEvent.offsetX, e.offsetY - dragEvent.offsetY, dragEvent.target.clientWidth, dragEvent.target.clientHeight);
})
svg
{
  background-color: #ddd;
}

img
{
  cursor: pointer;
}
<script src="http://cdnjs.cloudflare.com/ajax/libs/raphael/2.1.0/raphael-min.js"></script>

<img draggable="true" id="test" src="https://www.gravatar.com/avatar/a4d924e65b84f1572ea3598437aa5559?s=48&d=identicon&r=PG&f=1" /><span>You can drop the image on the grey zone</span>

Upvotes: 1

Related Questions