Search code examples
fabricjs

Working with FebricJs and outputting toDataURL


I found a code on your site that loads an image using FebricJs into the browser. Then you can twist it and resize it and pass it base64 to the output. Loading goes fine, I edit its size and when I click on the output in , the original image is displayed without changes. https://jsfiddle.net/sujitkm/p51zwL50/ I have not worked with this script, help me understand why this is happening? I want to get the modified image in canvas.toDataURL (). Thanks.

 var canvas = new fabric.Canvas('canvas');
            document.getElementById('file').addEventListener("change", function (e) {
                var file = e.target.files[0];
                var reader = new FileReader();
                reader.onload = function (f) {
                    var data = f.target.result;
                    fabric.Image.fromURL(data, function (img) {
                        var oImg = img.set({left: 50, top: 100, angle: 00}).scale(0.9);
                        canvas.add(oImg).renderAll();
                        var a = canvas.setActiveObject(oImg);
                         oImg.setCoords();
                    var dataURL = canvas.toDataURL({ format: 'jpeg', quality: 0.8 });
                                                canvas.renderAll();
     console.log("Canvas Image " + dataURL);
                document.getElementById('txt').href=dataURL;
});
                 };
                reader.readAsDataURL(file);  
               
                
            });

Solution

  • There is old url in href, which was set only when you add the object to canvas and didn't change after the object transformation. This is the reason why there is the old image. You need to use fires from doc for it. I prepared code, it works:

    const canvas = new fabric.Canvas('canvas');
    document.getElementById('file').addEventListener('change', function(e) {
      const file = e.target.files[0];
      const reader = new FileReader();
      reader.onload = function(f) {
        const data = f.target.result;
        fabric.Image.fromURL(data, function(img) {
          const oImg = img.set({ left: 50, top: 100, angle: 00 }).scale(0.9);
          canvas.add(oImg).renderAll();
          const a = canvas.setActiveObject(oImg);
        });
      };
      reader.readAsDataURL(file);
    });
    
    canvas.on('object:modified', () => {
      const dataURL = canvas.toDataURL({ format: 'jpeg', quality: 0.8 });
    
      console.log('Canvas Image ' + dataURL);
      document.getElementById('txt').href = dataURL;
    });