FabricJS clipPath ToJSON
by Steve Eberhardt
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/2.7.0/fabric.js"></script>
<canvas id="c1"></canvas>
<button id="toJSON">Save/Load JSON</button>
<canvas id="c2"></canvas>
CSS
canvas {
border: 1px solid #999;
}
JavaScript
var canvas = new fabric.Canvas('c1', {
width: 300,
height: 250
});
var canvas2 = new fabric.Canvas('c2', {
width: 300,
height: 250
});
var clipPath = new fabric.Circle({ radius: 100, top: 0, left: 50 });
var group = new fabric.Group([
new fabric.Rect({ width: 100, height: 100, fill: 'red' }),
new fabric.Rect({ width: 100, height: 100, fill: 'yellow', left: 100 }),
new fabric.Rect({ width: 100, height: 100, fill: 'blue', top: 100 }),
new fabric.Rect({ width: 100, height: 100, fill: 'green', left: 100, top: 100 })
]);
canvas.clipPath = clipPath;
canvas.add(group);
$('#toJSON').on('click', function(){
var json = canvas.toJSON();
console.log(json);
canvas2.loadFromJSON(json, function() {
canvas.requestRenderAll();
});
});
fabric.StaticCanvas.prototype._toObjectMethod = function (methodName, propertiesToInclude) {
var clipPath = this.clipPath, data = {
version: fabric.version,
objects: this._toObjects(methodName, propertiesToInclude),
};
if (clipPath) {
data.clipPath = this._toObject(this.clipPath, methodName, propertiesToInclude);
}
fabric.util.object.extend(data, this.__serializeBgOverlay(methodName, propertiesToInclude));
fabric.util.populateWithProperties(this, data, propertiesToInclude);
return data;
};