Prateek Saini
Prateek Saini

Reputation: 173

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);
    });

Upvotes: 2

Views: 3978

Answers (1)

Cathy
Cathy

Reputation: 377

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.

Upvotes: 5

Related Questions