如何在 fabric.js 中导出带有自定义属性的 SVG?

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

有没有办法向对象添加自定义属性并在导出的 SVG 上获取它们?

我正在使用这种方式进行 JSON 导出。但它不适用于 SVG 导出。

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

当我使用 canvas.toSVG() 导出我的 canvas 时,自定义属性将不会导出。

我一直在寻找这个问题的解决方案,但我无法在网络上的任何地方找到它。于是下载了最新版的fabricjs,自己修改。最新版本的fabricjs默认会导出id。所以我们可以只修改那部分代码以从 canvas.

导出你想要的任何自定义属性

在您的结构 canvas 对象中,初始化您想要的自定义属性类型。 例如: my_canvas.custom_attribute_array = ["room_id","class","id"];

然后修改fabricjs的getsvgId函数

/**
 * Returns id attribute for svg output
 * @return {String}
 */
getSvgId: function() {
  if(this.canvas.custom_attribute_array){
    console.log(this.canvas.custom_attribute_array); 
    var custom_result = [];
    for(var i in this.canvas.custom_attribute_array){
        var custom_attribute = this.canvas.custom_attribute_array[i];
        if(this[custom_attribute]){
            var val =  this[custom_attribute];
            if(typeof val == "string"){
                val = '"'+val+'"';     
            }
            custom_result.push(custom_attribute + '=' + val); 
        }    
    }
    console.log(custom_result);
    if(custom_result){
        return custom_result.join(" ") + " ";   
    }
  }
  else{
    return this.id ? 'id="' + this.id + '" ' : '';
  }
},

您可以像这样覆盖现有的 toSVG 函数。

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)