Search code examples
drag-and-drophtml5-canvasfabricjs

Drag and drop the image from pc(user system) to canvas using fabric.js


Hey I am working on a project where I need drag and drop the image from PC(user system) to html5 canvas using fabric.js, as I got the code for div(taken as dropdown) to canvas but struck with PC(user system) to canvas can anyone help me please how to proceed further.

Here is the code I have done so far

 var js_c_drawing, activeObject = null;
        $(document).ready(function () {
            setDrawingCanvasCoords();
            js_c_drawing = new fabric.Canvas('c_drawing');
            js_c_drawing.calcOffset();
            if (typeof fabric.instances != "undefined") fabric.instances.push(js_c_drawing);
        });
        function setDrawingCanvasCoords() {
            var wHeight = $(window).height() - 100;
            var wWidth = $(window).width() - 164;
            var drawingStyle = 'border:4px solid gray;top:20px;position:relative;background-color:black;' + 'width:' + wWidth + 'px; height:' + wHeight + 'px';
            $("#divDrawing").attr('style', drawingStyle);
        }       
        function showToolMenu(shapeMenu) {
            var divShapesId = 'divShapes';
            var divElement = $('#' + divShapesId);
            var ele = document.getElementById('a' + shapeMenu);
            elePosition = findPos(ele);
            document.getElementById(divShapesId).style.left = elePosition[0] + 'px';
            document.getElementById(divShapesId).style.top = elePosition[1] + (ele.offsetHeight) + 'px';
            document.getElementById(divShapesId).style.zIndex = 100;
            divElement.show();
            var url = baseurl + shapeMenu;
            $(divElement).load(url);
        }
        function hideToolMenu() {
            var divShapesId = 'divShapes';
            var divElement = $('#' + divShapesId);
            document.getElementById(divShapesId).style.zIndex = 20;
            divElement.hide(2000);
        }   
        function findPos(obj) {
            var curleft = curtop = 0;
            if (obj.offsetParent) {
                curleft = obj.offsetLeft
                curtop = obj.offsetTop
                while (obj = obj.offsetParent) {
                    curleft += obj.offsetLeft
                    curtop += obj.offsetTop
                }

            }
            return [curleft, curtop];
        }

I already tried to use http://www.html5rocks.com/en/tutorials/file/dndfiles/ this but it is showing image size etc and I have tried http://jsfiddle.net/natchiketa/w8kkc/ this code to do with PC(user system) and canvas but unsuccessful.


Solution

  • Finally I got the solution http://jsfiddle.net/rodrigopandini/gj7HT/ using above two links. Here is the code

    function handleDragStart(e) {
        [].forEach.call(images, function (img) {
            img.classList.remove('img_dragging');
        });
        this.classList.add('img_dragging');
    }
    
    function handleDragOver(e) {
        if (e.preventDefault) {
            e.preventDefault(); // Necessary. Allows us to drop.
        }
    
        e.dataTransfer.dropEffect = 'copy'; // See the section on the DataTransfer object.
        // NOTE: comment above refers to the article (see top) -natchiketa
    
        return false;
    }
    
    function handleDragEnter(e) {
        // this / e.target is the current hover target.
        this.classList.add('over');
    }
    
    function handleDragLeave(e) {
        this.classList.remove('over'); // this / e.target is previous target element.
    }
    
    function handleDrop(e) {    
        // this / e.target is current target element.
    
        /*
        if (e.stopPropagation) {
            e.stopPropagation(); // stops the browser from redirecting.
        }
        */
    
        e.stopPropagation(); // Stops some browsers from redirecting.
        e.preventDefault(); // Stops some browsers from redirecting.
    
        // handle desktop images
        if(e.dataTransfer.files.length > 0){
    
            var files = e.dataTransfer.files;
            for (var i = 0, f; f = files[i]; i++) {
    
                // Only process image files.
                if (f.type.match('image.*')) {            
                    // Read the File objects in this FileList.
                    var reader = new FileReader();
                    // listener for the onload event
                    reader.onload = function(evt) {
                        // create img element
                        var img = document.createElement('img');
                        img.src= evt.target.result;                        
    
                        // put image on canvas
                        var newImage = new fabric.Image(img, {
                            width: img.width,
                            height: img.height,
                            // Set the center of the new object based on the event coordinates relative to the canvas container.
                            left: e.layerX,
                            top: e.layerY
                        });
                        canvas.add(newImage);
                    };
                   // Read in the image file as a data URL.
                   reader.readAsDataURL(f);
                }
            }
        }  
        // handle browser images
        else{        
           var img = document.querySelector('#images img.img_dragging');
            var newImage = new fabric.Image(img, {
                width: img.width,
                height: img.height,
                // Set the center of the new object based on the event coordinates relative to the canvas container.
                left: e.layerX,
                top: e.layerY
            });
            canvas.add(newImage); 
        } 
    
        return false;
    }
    
    function handleDragEnd(e) {
        // this/e.target is the source node.
        [].forEach.call(images, function (img) {
            img.classList.remove('img_dragging');
        });
    }
    
    if (Modernizr.draganddrop) {
        // Browser supports HTML5 DnD.
    
        // Bind the event listeners for the image elements
        var images = document.querySelectorAll('#images img');
        [].forEach.call(images, function (img) {
            img.addEventListener('dragstart', handleDragStart, false);
            img.addEventListener('dragend', handleDragEnd, false);
        });
        // Bind the event listeners for the canvas
        var canvasContainer = document.getElementById('canvas-container');
        canvasContainer.addEventListener('dragenter', handleDragEnter, false);
        canvasContainer.addEventListener('dragover', handleDragOver, false);
        canvasContainer.addEventListener('dragleave', handleDragLeave, false);
        canvasContainer.addEventListener('drop', handleDrop, false);
    } else {
        // Replace with a fallback to a library solution.
        alert("This browser doesn't support the HTML5 Drag and Drop API.");
    }