How to export SVG with custom attributes in fabric.js?

Viewed 1771

Is there a way to add custom attributes to objects and get them on exported SVG?

I'm using this way for JSON exports. But it's not working for SVG exports.

canvas.item(0).foo = 'bar'; // custom property
var json = JSON.stringify(canvas.toJSON(['foo'])); // include that property in json
canvas.clear();
canvas.loadFromJSON(json);
canvas.item(0).foo; // "bar" <-- the property is preserved

When I export my canvas using canvas.toSVG() the custom attributes will not exported.

2 Answers

You can override the existing toSVG function like this.

var circle = new fabric.Circle ({
          radius: 40,
          left: 50,
          top: 50,
          fill: 'rgb(0,255,0)',
          opacity: 0.5,
          id: 'hello'
    });
    circle.toSVG = (function(toSVG) {
      return function(){
        var svgString = toSVG.call(this);
        var domParser = new DOMParser();
        var doc = domParser.parseFromString(svgString, 'image/svg+xml');
        var parentG = doc.querySelector('circle')
        parentG.setAttribute('id', this.id);
        return doc.documentElement.outerHTML;
      }
      })(circle.toSVG)
Related