kineticjs drag and drop image from dom into canvas

2019-03-28 12:57发布

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条回答
霸刀☆藐视天下
2楼-- · 2019-03-28 13:32

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/

查看更多
登录 后发表回答