How to drag and drop between canvases in Fabric.js

前端 未结 2 1596
有刺的猬
有刺的猬 2021-02-02 04:52

I understand Fabric.js have built-in support on drag-n-drop within the same canvas.

How can we make it work for multiple canvas?

Or from an non-canvas html eleme

2条回答
  •  猫巷女王i
    2021-02-02 05:11

    Use

     canvas.observe("object:moving", function (event) {});
    

    If event.e.clientY and event.e.clientX are outside the canvas, then:

    var activeObject = canvas.getActiveObject();
    

    Store in global dragImage var

    activeObject.clone(function (c) { dragImage = c; });
    
    canvas.remove(activeObject);
    

    Then in window mouse move event you can place an img with src = dragImage.src and follow the cursor.

    function mousemove(e){
    if (dragImage != null) {
        $("#dragimage").show();
        $("#dragimage").css("left", e.clientX); 
        $("#dragimage").css("top", e.clientY);
        return;
    }else{
    $("#dragimage").hide();
    }
    }
    

    On a window event mouseup, if dragImage != null and new coordinates are inside a fabric.js canvas, just newcanvas.add(dragImage).

    mouseup event:

    if (dragImage != null) {
                $([canvas, canvas2]).each(function (i, v) {
                    if (Intersect([event.clientX, event.clientY],$(v.wrapperEl))) {
                        dragImage.left = event.clientX - $(v.wrapperEl).offset().left;
                        dragImage.top = event.clientY - $(v.wrapperEl).offset().top;
                        v.add(dragImage);
                    }              
    
                });
    
                dragImage = null;
            }
    

    Helper Intersect function:

    function Intersect(point, element) {
        return (      point[0] > element.offset().left
                   && point[0] < element.offset().left + element.width()
                   && point[1] < element.offset().top + element.height()
                   && point[1] > element.offset().top
                );    
    }
    

    css for #dragimage:

    #dragimage
    {
        opacity:0.5;
        max-width:100px;
        max-height:200px;
        position:fixed;
        top:0px;
        left:0px;
        z-index:90000;
    }
    

    I can't do a fiddle but i implemented this on our mega huge photo album editor in less than 30 minutes. Works for text too but for text you must use dragImage=getActiveObject().clone() Any questions feel free to ask.

提交回复
热议问题