2016-03-08 109 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 + '" ' : ''; 
    } 
}, 
相關問題