Custom SVG Object in fabric.js
Custom SVG Object
by rodrigopandini
HTML
<script src="https://raw.github.com/kangax/fabric.js/master/dist/all.js"></script>
<button id="btnAddSVG">1 - Add SVG</button>
<button id="btnAddCustomSVG">2 - Add Custom SVG</button>
<button id="btnAddCreatorPath">3 - Add CreatorPath</button>
<button id="btnSerializeToJSON">4 - Serialize to JSON</button>
<button id="btnConsoleLogJSON">5 - console.log(json)</button>
<button id="btnClearCanvas">6 - Clear Canvas</button>
<button id="btnRestore">7 - Restore</button>
<canvas id="canvas" width="400" height="400"></canvas>
CSS
canvas{
border-width: 1px;
border-style: solid;
border-color: #333;
}
JavaScript
var src = 'http://177.71.252.215/star.svg';
var src2 = 'http://fabricjs.com/assets/10.svg';
var json;
var canvas = new fabric.Canvas("canvas");
//////////////////////////////////////////////////////////////
// create CustomSVG class from Path class
// extends Path putting "possibleColors" atribute (array of strings - hexadecimal colors)
fabric.CustomSVG = fabric.util.createClass(fabric.Path, {
type: 'custom-svg',
initialize: function(paths, options) {
this.callSuper('initialize', paths, options);
options && this.set('possibleColors', options.possibleColors);
},
toObject: function() {
return fabric.util.object.extend(this.callSuper('toObject'),
{possibleColors: this.possibleColors});
}
});
fabric.CustomSVG.fromObject = function(object) {
var paths = instantiatePaths(object.paths);
return new fabric.CustomSVG(object.paths, object);
};
fabric.CustomSVG.async = false;
function instantiatePaths(paths) {
for (var i = 0, len = paths.length; i < len; i++) {
if (!(paths[i] instanceof fabric.Object)) {
var klassName = camelize(capitalize(paths[i].type));
paths[i] = fabric[klassName].fromObject(paths[i]);
}
}
return paths;
}
///////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////
// CreatorPath
fabric.CreatorPath = fabric.util.createClass(fabric.Path, {
type: "creator-svg",
initialize: function(path, options){
console.log("path");
this.callSuper("initialize", path, options);
options && this.set("name", options.name);
},
toObject: function(){
return fabric.util.object.extend(this.callSuper("toObject"), {name: this.name});
}
});
fabric.CreatorPath.fromObject = function(object){
var paths = instantiatePaths(object.paths);
return new fabric.CreatorPath(paths, object);
};
fabric.CreatorPath.async = false;
function instantiatePaths(paths){
for(var i = 0, len = paths.length; i < len; i++){
...