2016-03-08 124 views
3

有没有一种方法可以将自定义属性添加到对象并在导出的SVG上获取它们?如何使用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()导出画布时,不会导出自定义属性。

回答

0

我正在寻找解决方案来解决这个问题,我无法在网络上的任何地方找到它。所以我下载了最新版本的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 + '" ' : ''; 
    } 
}, 
相关问题