Dragging and Dropping Images into FabricJS Canvas

In this example below you will see how to do a Dragging and Dropping Images into FabricJS Canvas with some HTML / CSS and Javascript

This awesome code was written by dizzyluo, you can see more from this user in the personal repository.
You can find the original code on Codepen.io
Copyright dizzyluo ©


  • HTML
  • JavaScript
<!DOCTYPE html>
<html lang="en" >

  <meta charset="UTF-8">
  <title>Dragging and Dropping Images into FabricJS Canvas</title>


  <div id="canvas-container">
    <canvas id="c" width="1000" height="1000" style="border: 1px solid black;"></canvas>
  <script src='https://cdnjs.cloudflare.com/ajax/libs/modernizr/2.8.3/modernizr.min.js'></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.6.2/fabric.min.js'></script>


    <script  src="js/index.js"></script>



/*Downloaded from https://www.codeseek.co/dizzyluo/dragging-and-dropping-images-into-fabricjs-canvas-LZbzYv */
(function() {
			var canvas_container = document.getElementById('canvas-container');
			var canvas = new fabric.Canvas('c');
			var ctx = canvas.getContext('2d');
			canvas_container.addEventListener('drop', function (e) {
				e = e || window.event;
				if (e.preventDefault) {
				var dt = e.dataTransfer;
				var files = dt.files;
				for (var i=0; i<files.length; i++) {
					var file = files[i];
					var reader = new FileReader();
					//attach event handlers here...
					reader.onload = function (e) {
						var img = new Image();
						img.src = e.target.result;
						var imgInstance = new fabric.Image(img, {
							left: 100,
							top: 100,
				return false;
			canvas_container.addEventListener('dragover', cancel);
			canvas_container.addEventListener('dragenter', cancel);

			function cancel(e) {
				if (e.preventDefault) { e.preventDefault(); }
				return false;
			// fabric.Object.prototype.transparentCorners = false;

			var rect = new fabric.Rect({
				left: 100,
				top: 50,
				width: 100,
				height: 100,
				fill: 'green',
				angle: 20,
				padding: 10