8

I was trying to use FileSaver.js with a Fabric.canvas object, but it seems that Fabric js has no blob option.

I'm using the Meteor framework by the way.

How can I export a Fabric canvas without using the basic canvas.toDataUrl ?'

Thanks :)

Ynnad
  • 303
  • 4
  • 18
  • 1
    https://github.com/eligrey/FileSaver.js, the github of FileServer – Ynnad Dec 01 '15 at 19:32
  • 1
    you can easily convert your dataURI string to a blob http://stackoverflow.com/questions/4998908/convert-data-uri-to-file-then-append-to-formdata/5100158#5100158 – Kaiido Dec 02 '15 at 06:34

2 Answers2

8

You can achieve this by using the native Canvas element.

var canvas = new fabric.Canvas("canvas");

// ... your code here ...

canvas.getElement().toBlob(function(blob) {
  saveAs(blob, "canvas.png");
});

And if you want this to work with Safari, you can use the Sebastian Tschan Javascript Canvas to Blob polyfill.

Florent B.
  • 1,193
  • 2
  • 10
  • 12
1

Fabric has no direct option of Blob. But you can export it in json by canvas.toJSON() or in image by canvas.toDataURL(). Then you convert the data in blob simply doing this.

Export fabric canvas in blob:

  var data = JSON.stringify(canvas.toJSON()),           
        blob = new Blob([data], {type: "octet/stream"});

or

  var data = canvas.toDataURL(),           
        blob = new Blob([data], {type: "octet/stream"});

See in fiddle

Mahbubur Rahman
  • 4,961
  • 2
  • 39
  • 46
  • Thanks, that's a pretty good idea. The problem is that it doesn't work with Safari... – Ynnad Dec 02 '15 at 09:54
  • For me, the png gets outputted as base64 data. So it's an invalid image file. Upon debugging, I notice that variable blob2's data property has the same base64 data set to it as variable data2. Isn't the blob function supposed to turn this base64 into binary data? – Jay Feb 13 '19 at 16:48