Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert canvas to SVG with embedded image base64 in fabricjs

I have fabricjs canvas with image, which I loaded by fabric.Image.fromURL() method.

I need export it to SVG, but I want to export image as embedded source in base64, not as a link.

How can I do it? Is it any way to load image as a source not as a link?

Example code:

Loading image:

fabric.Image.fromURL('./assets/people.jpg', function (image) {
    image.set({
        left: 10,
        top: 30
    });
    canvas.add(image);
};

Exporting to SVG:

canvas.toSVG();

In exported SVG I have:

<image xlink:href="http://localhost:8383/app/assets/people.png" />

But I want it in base64 like:

<image xlink:href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAe8AAAKuCAYAAACIZZSZAAAAAXNSR0IArs4c6QAAAARnQU1BAACx(...)" />
like image 953
Jacek Gzel Avatar asked May 09 '16 14:05

Jacek Gzel


2 Answers

There is no option but you can easily achieve it like this: Image has a method that is called 'getSvgSrc';

override it like this:

fabric.Image.prototype.getSvgSrc = function() {
  return this.toDataURLforSVG();
};

fabric.Image.prototype.toDataURLforSVG = function(options) {
  var el = fabric.util.createCanvasElement();
        el.width  = this._element.naturalWidth || this._element.width;
        el.height = this._element.naturalHeight || this._element.height;
  el.getContext("2d").drawImage(this._element, 0, 0);
  var data = el.toDataURL(options);
  return data;
};

In this way you should be able to obtain an integrated image for the svg.

like image 130
AndreaBogazzi Avatar answered Oct 22 '22 21:10

AndreaBogazzi


you can use the toSVG method :

rasterizeSVG () {
    let w = window.open('')
    w.document.write(this.canvas.toSVG())
    return 'data:image/svg+xml;utf8,' + encodeURIComponent(this.canvas.toSVG())
  }

or :

rasterize() {
  if (!fabric.Canvas.supports('toDataURL')) {
    alert('This browser doesn\'t provide means to serialize canvas to an image');
  }
  else {
    var image = new Image();
    image.src = this.canvas.toDataURL('png')
    var w = window.open("");
    w.document.write(image.outerHTML);
  }
}
like image 32
ouzza brahim Avatar answered Oct 22 '22 20:10

ouzza brahim