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

Thumbnail
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 ©

Technologies

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

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

<body>

  <div id="canvas-container">
    <canvas id="c" width="1000" height="1000" style="border: 1px solid black;"></canvas>
</div>
  <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>




</body>

</html>

/*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) {
				console.log("DROP");
				e = e || window.event;
				if (e.preventDefault) {
					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,
						});
						canvas.add(imgInstance);
					}
					reader.readAsDataURL(file);
				}
				
				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
			});
			canvas.add(rect);
		})();

Comments