如何在结构中导出具有自定义属性的 SVG.js

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

本文关键字:自定义属性 SVG js 结构      更新时间:2023-09-26

有没有办法将自定义属性添加到对象并在导出的 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() 导出画布时,自定义属性将不会导出。

您可以像这样覆盖现有的 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)

我正在寻找解决此问题的方法,但我无法在网上的任何地方找到它。所以我下载了最新版本的fabricjs并自己修改了它。最新版本的fabricjs默认会导出id。因此,我们可以修改代码的该部分,以从画布中导出所需的任何自定义属性。

在结构画布对象中,初始化所需的自定义属性类型。例如: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 + '" ' : '';
  }
},