简体   繁体   中英

How can I add multiple images from local disk to canvas using Fabric.js?

I'm creating an Image Collage application in HTML5 canvas using Fabric.js . I want that user can drag and drop file to 'File Drag and Drop Area' and also he can 'Choose File' from his local disk. Please help me in implementing this.

I'm using this code to add multiple images. Now, I want to add images from my Local Disk onto Canvas.

//Image 1
 fabric.Image.fromURL('/3.jpg', function (img) {
        var oImg = img.set({ left: 300, top: 300, angle: -15 }).scale(0.9);
        canvas.add(oImg).renderAll();
        canvas.setActiveObject(oImg);

    });

 //Image 2
 fabric.Image.fromURL('/bokeh.jpg', function (img) {
        var oImg = img.set({ left: 300, top: 300, angle: -15 }).scale(0.9);
        canvas.add(oImg).renderAll();
        canvas.setActiveObject(oImg);
    });

Hey I have the solution for drag and drop and choose file but not in one answer actually I have two different separate solutions Drag and Drop: http://jsfiddle.net/rodrigopandini/gj7HT/

Choose file:

<input type="file" id="imgLoader">

    <canvas id="c" width="300" height="300"></canvas>
<script src="https://raw.github.com/kangax/fabric.js/master/dist/all.js"> </script>
<script type="text/javascript>
canvas = new fabric.Canvas('c');

document.getElementById('imgLoader').onchange = function handleImage(e) {
    var reader = new FileReader();
    reader.onload = function (event) { console.log('fdsf');
        var imgObj = new Image();
        imgObj.src = event.target.result;
        imgObj.onload = function () {
            // start fabricJS stuff

            var image = new fabric.Image(imgObj);
            image.set({
                left: 250,
                top: 250,
                angle: 20,
                padding: 10,
                cornersize: 10
            });
            //image.scale(getRandomNum(0.1, 0.25)).setCoords();
            canvas.add(image);

            // end fabricJS stuff
        }

    }
    reader.readAsDataURL(e.target.files[0]);
}
</script>

U can try it these codes in one script.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM