Is there a way to add custom attributes to objects and get them on exported SVG?
I'm using this way for JSON exports. But it's not working for SVG exports.
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
When I export my canvas using canvas.toSVG() the custom attributes will not exported.
I was looking for a solution to this problem and I was not able to find it anywhere on the web. So I downloaded the latest version of fabricjs and modified it myself. The latest version of fabricjs will export the id by default. So we can just modify that part of the code to export whatever custom attributes you want from the canvas.
In your fabric canvas object, initiailize the type of custom attributes you want. For example: my_canvas.custom_attribute_array = ["room_id","class","id"];
Then modify the fabricjs getsvgId function.
/**
* 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 + '" ' : '';
}
},