kineticjs drag and drop image from dom into canvas

2019-03-28 13:37发布

问题:

I have an image loaded on the dom already, and I want to be able to drag that image into a canvas and drop it into the canvas and create a kineticjs object out of it.

I don't know how to make the image draggable, and I don't know how to make the canvas react to drag and drop events that already exist on the dom. Can someone show me how to do this?

Most of the tutorials show how to drag and drop from within the canvas, or the file system, I'm looking how to drag from the DOM to the canvas.

Background info: I want to have a menu system or a bunch of thumbnails that a user can drag and drop into the canvas to expand the photo.

Thanks in advance!

回答1:

No problem!

1 You have to use "drag and drop" from html5. Tutorial: http://www.html5rocks.com/en/tutorials/dnd/basics/

2 setup dom event to image:

var dragSrcEl = null;
//image
document.getElementById("yoda").addEventListener('dragstart',function(e){
       dragSrcEl = this;
});

3 Events for container object:

var con = stage.getContainer();        
con.addEventListener('dragover',function(e){
    e.preventDefault(); // !!important
});
//insert image to stage
con.addEventListener('drop',function(e){
    var image = new Kinetic.Image({
       draggable : true
    });
    layer.add(image);
    imageObj = new Image();
    imageObj.src = dragSrcEl.src;
    imageObj.onload = function(){
        image.setImage(imageObj)
        layer.draw()
    };
 });

And of course full example: http://jsfiddle.net/lavrton/n4w44/