Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 660
Ynnad Avatar asked Dec 01 '15 19:12

Ynnad


2 Answers

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.

like image 73
Florent B. Avatar answered Oct 14 '22 11:10

Florent B.


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

like image 41
Mahbubur Rahman Avatar answered Oct 14 '22 12:10

Mahbubur Rahman