Jacek Gzel Jacek Gzel - 2 months ago 47
Javascript Question

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(...)" />

Answer

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;
  el.height = this._element.naturalHeight;
  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.

Comments