Search code examples
canvasfabricjs

How to Replace the Existing image with the new Image in canvas Using the Fabric.js


I need to replace the existing image with the new image from file upload from the computer, I want to replace the image with a newly uploaded image. Here is the code (JSFiddle).

var canvas = new fabric.Canvas('c');

function addImage () {
    fabric.Image.fromURL('http://lorempixel.com/400/200', function (img) {
     img.set({ 'left': 50 });
      img.set({ 'top': 50 });
      img.scaleToWidth(100);
      img.scaleToHeight(100);
      canvas.add (img);
    });
}

addImage();
canvas {
    border:1px solid #000;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.6.2/fabric.min.js"></script>
<canvas id="c" width="400" height="200"></canvas>
<span><input type="file" name="" id="span"></span>


Solution

  • You could accomplish such, in the following way ...

    var canvas = new fabric.Canvas('c');
    
    function addImage(imgLink) {
        fabric.Image.fromURL(imgLink, function(img) {
            img.set({ 'left': 50 });
            img.set({ 'top': 50 });
            img.scaleToWidth(100);
            img.scaleToHeight(100);
    				
            var objs = canvas.getObjects();
            if (objs.length) {
                objs.forEach(function(e) {
                    if (e && e.type === 'image') {
                        e._element.src = imgLink;
                        canvas.renderAll();
                    }
                });
            } else canvas.add(img);
        });
    }
    
    addImage('http://lorempixel.com/400/200');
    
    // file upload
    var span = document.querySelector('#span');
    span.onchange = function(e) {
        var file = e.target.files[0];
        var reader = new FileReader();
        reader.onload = function(file) {
            addImage(file.target.result);
        }
        reader.readAsDataURL(file);
    }
    canvas {
      border:1px solid lightgrey;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.6.2/fabric.min.js"></script>
    <canvas id="c" width="400" height="200"></canvas>
    <span><input type="file" name="" id="span"></span>