Search code examples
javascriptfabricjsfabricjs2

Export canvas on fabric.js to an image


I'm using fabric.js to make a draw and export the canvas to a .png without background. The thing is that I've been searching and this is the only thing that, in a way, makes sense to me:

document.getElementById("downloadbtn").onclick = saveImage();
function saveImage(c) {
  this.href = canvas.toDataURL({
      format: 'png',
      quality: 0.8
  });
  this.download = 'testimage.png'
}

But it doesn't work... I've also tried a bunch of different stuff but the same thing happens:

Failed to execute toDataURL... error in the console.

Any helps? Ty


Solution

  • For those who had the same issue as me, the thing is:

    You can save easily the canvas to an image, but you can't do it if you have an image inside the canvas, let me explain. If you have imported a nonlocal image into the canvas (like pasting an image with fromURL), the CORS of the web will detect this as a probable threat for the system, and will block the action.

    For me, saving the canvas without the url image is fine, so I have no other solution for those who try to save the canvas with an external image, but maybe save first locally the image and then save it will work for you.

    Hope it can help!