Jacek Gzel Jacek Gzel - 1 year ago 192
Javascript Question

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

I have fabricjs canvas with image, which I loaded by


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) {
left: 10,
top: 30

Exporting to SVG:


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 Source

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.