Ynnad
Ynnad

Reputation: 303

FileSaver.js with a Fabric canvas

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 :)

Upvotes: 8

Views: 3936

Answers (2)

Florent B.
Florent B.

Reputation: 1233

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.

Upvotes: 8

Mahbubur Rahman Manik
Mahbubur Rahman Manik

Reputation: 5161

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

Upvotes: 1

Related Questions