Canvas toJson
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/2.2.3/fabric.js"></script>
<canvas id="paper" width="400" height="200" style="border:1px solid #ccc"></canvas>
<button id="save">Save to JSON</button>
<button id="restore">Restore form JSON</button>
SCSS
#paper {
border: solid 1px red;
}
JavaScript
fabric.ContainerRect = fabric.util.createClass(fabric.Rect, {
type: 'container-rect',
initialize: function(options) {
this.set({
clipTo: function(ctx){
ctx.rect(-this.width / 2, -this.height / 2, this.width, this.height);
}
});
this.callSuper('initialize', options);
this.on('moving', function(){
// console.log('Red is moving...');
});
},
_render: function(ctx) {
this.callSuper('_render', ctx);
}
});
fabric.ContainerRect.fromObject = function(object, callback) {
return fabric.Object._fromObject('ContainerRect', object, callback);
};
fabric.Paragraph = fabric.util.createClass(fabric.Textbox, {
type: 'paragraph',
initialize: function(text, options) {
this.callSuper('initialize', text, options);
},
_render: function(ctx) {
this.callSuper('_render', ctx);
}
});
//fabric.Paragraph.fromObject = function(object, callback) {
//return fabric.Object._fromObject('Paragraph', object, callback);
//};
fabric.Paragraph.fromObject = function(object, callback) {
return fabric.Object._fromObject('Paragraph', object, callback, 'text');
};
//==========================================================================================
let store;
const canvas = new fabric.Canvas('paper');
const redBox = new fabric.ContainerRect({
left: 0,
top: 0,
width: 50,
height: 50,
fill: 'red'
});
const text = new fabric.Paragraph("Hello", {
left: 0,
top: 100,
width: 50,
height: 50,
fontWeight: 'bold',
fontStyle: 'italic',
fill: 'blue',
underline: true,
linethrough: true
});
canvas.add(redBox);
canvas.add(text);
canvas.renderAll();
$("#save").on('click', function(){
store = canvas.toJSON();
console.log(store);
});
$("#restore").on('click', function(){
canvas.loadFromJSON(store, function(){
// console.log('restored:', canvas.getObjects());
// canvas.renderAll();
});
});