Drag Fabric.js object from one canvas to another

2019-05-05 12:03发布

问题:

I am using Fabric.js to create design on any product. my some product has two canvas so I want to move fabric.Text from one canvas to another and I want to drag and drop Fabric canvas object to other Fabric canvases.

回答1:

I have absolutely no idea whether this is a good, bad or ugly way of doing things however I've put together a simple fiddle which achieves what you are after - the basic principle of what i've done is this:

encapsulate your canvas objects within an object, where the canvas id's are the object keys, for example

var canvases = {
    canvas1 : new fabric.Canvas('canvas1'),
    canvas2 : new fabric.Canvas('canvas2')
 }

this allows you to reference them easily later on.

Then on the canvas mouse:down event, if there is an active object capture a reference to it along with the id of the canvas (using activeObject = this.getActiveObject(); and this.lowerCanvasEl.id respectively within the mouse:down callback.

note: you could use the object:selected event in place of mouse:down, however if you drag an already selected object on the canvas, it doesn't fire.

Then I bound a callback to the document mouseup event using jQuery on - the purpose of the callback is to first detect whether the target is a canvas element, if it is we get the id of your fabric canvas, compare it to the id that we stored on the mouse:down event earlier, and if they are different add the activeObject that we stored earlier to the new canvas target like so canvases[canvasId].add(activeObject); at the end of the mouseup callback I clear the activeObject and initialCanvas variables - this prevents the user from simply clicking a canvas object and then clicking on the new canvas and simulates a seamless drag-and-drop.

full code is here: http://jsfiddle.net/uppzL/12/

I hope that it's helpful, i'm sure it needs refining and improving though, especially getting the object from canvas1 to snap back to it's original starting place or disappear completely, rather than just being stuck out of the viewport of the canvas.