How to Use Drag And Drop On HTML5 Canvas Element Using FabricJS

How to Use Drag And Drop On HTML5 Canvas Element Using FabricJS

15 Sep 2022
0 Comments
How to Use Drag And Drop On HTML5 Canvas Element Using FabricJS

Fabric.js is a powerful and simple Javascript HTML5 canvas library.

Reference link: http://fabricjs.com/

git repo. link: https://github.com/sahil-binekar/FabricJs-drag-and-drop
What is HTML Canvas?

The HTML <canvas> element is used to draw graphics, on the fly, via JavaScript.

The <canvas>

Canvas has several methods for drawing paths, boxes, circles, text, and adding images.


Step 1: Creating Html file

Create a simple HTML boilerplate, we will be using fabricJs including fabricJs CND.

Add some images inside the < body > tag, as we are going to drag and drop these images inside the canvas, write < img > tag as draggable = “true” and add event listener ondragstart = “ dragElement ( event )” (passing the argument event is important as the event is going to handle most of the things).

Create a canvas tag inside a tag, and make the div tag droppable by adding event listeners ondragover and on drop along with listeners.


Step 2: Writing javascript for drag and drop.

First, let’s initialize the fabric canvas on the window unload event.

Then on “ ondragstart” event calling the function dragElement(e).

With “ e.dataTransfer.setData(“id”, e.target.id) “ we are passing the drag target id to the drop function.

With allowDrop(e) function which is called on the “ ondragover “ event allows the canvas to be droppable.

The data i.e. “id” that we have passed from the “ dragElement(e)” method is received in the “ dropElement(e)” method using getData.

With help of the “ data “ variable instantiating the target image with imag variable.

Then creating the instance of fabric image ‘ img’ passing the target image i.e. imag, setting the left and top position with the help of event ‘ e’, with mouse dropped coordinates e.layerX and e.layerY.

To position, the element exactly at the mouse coordinates, reduce the coordinates to 80 from the left and 40 from the top, and to scale the image exactly as the image height and width ratio using scaleToWidth() and scaleToHeight() properties.

And finally adding the image to the canvas.

And some CSS for styling the canvas. Add this CSS in style.css and include it on your index page.

Demo linkhttps://fabric-drag-and-drop.herokuapp.com/

jsfiddle linkhttps://jsfiddle.net/Sahil999/rtbmy6hw/14/


Conclusion: FabricJs library does not provide drag and drops functionality by default, so fiddling with it to make it behave as we want. I hope this was helpful.

Thank you




Leave a comment: