如何在结构中导出具有自定义属性的 SVG.js
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() 导出画布时,自定义属性将不会导出。
您可以像这样覆盖现有的 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 + '" ' : '';
}
},
相关文章:
- 设置自动分隔符的自定义属性
- 与ng attr myCustomAttribute匹配的自定义属性指令
- 获取自定义属性的值
- 如何创建自定义属性以添加if.bind
- 动态更新Angular2指令中自定义属性的值
- 使用jQuery更改输入字段的自定义属性
- 在 Javascript 生成的列表中,如何将自定义属性添加到 标记
- 设置 HTML 自定义属性与在 ID 属性中存储信息
- 是否可以在 Polymer 中的
节点上使用自定义属性以获得漂亮的 API - 为什么克隆节点排除自定义属性
- 将自定义属性添加到 vuejs 组件
- 使用原型对象向javascript对象添加自定义属性和方法的建议
- 正在设置自定义属性名称
- datalist获取选定的值和自定义属性(无事件)
- 如何使用javascript获取元素的自定义属性值
- 在jQuery方法中编写自定义属性的正确语法是什么
- 自定义属性jquery Datatables
- 使用 css() 更改自定义属性不起作用
- 如何在结构中导出具有自定义属性的 SVG.js
- 是否可以将SVG对象的自定义属性设置为数字而不是字符串?