Canvas toJson
by Eugene Vilder
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/2.2.3/fabric.js"></script>
<img id="image" />
<canvas id="paper" width="400" height="400" style="border:1px solid #ccc"></canvas>
<button id="save">Save to JSON</button>
<button id="restore">Restore form JSON</button>
<button id="left"><-</button>
<button id="right">-></button>
<button id="rotate">R</button>
SCSS
#paper {
border: solid 1px red;
}
JavaScript
fabric.ImageContainer = fabric.util.createClass(fabric.Rect, {
type: 'image-container',
initialize: function(options) {
options || (options = { });
options.content || (options.content = { });
options.content.angle = options.content.angle || 0;
this.callSuper('initialize', options);
this.set({
objectCaching: false,
ddpPreviousCenter: this.getCenterPoint()
});
this.on('scaling', function(el){
this.set({
width: this.width * this.scaleX,
height: this.height * this.scaleY,
scaleX: 1,
scaleY: 1
});
this.setCoords();
this._drawImage();
}.bind(this));
this.on('modified', function(el){
this._updateContentCoords();
}.bind(this));
this._drawImage();
},
_updateContentCoords: function(){
const ddpPreviousCenter = {...this.ddpPreviousCenter};
const content = {...this.content};
const shiftX = this.getCenterPoint().x - ddpPreviousCenter.x;
const shiftY = this.getCenterPoint().y - ddpPreviousCenter.y;
content.left += shiftX;
content.top += shiftY;
this.set({
ddpPreviousCenter: this.getCenterPoint(),
content
});
},
rotateContent: function(){
this.content.angle += 5;
this.setCoords();
this._drawImage();
},
moveContent: function(direction){
if ( direction === 'left' ) {
this.content.left -= 10;
} else {
this.content.left += 10;
}
this.setCoords();
this._drawImage();
},
_drawImage: function() {
const scaleFactor = 1;
const imgSrc = [
'https://picsum.photos/',
this.content.width * scaleFactor,
'/',
this.content.height * scaleFactor
].join('');
fabric.Image.fromURL(imgSrc, function(img) {
img.set({
left: this.content.left - this.left + this.content.width / 2,
top: this.content.top - this.top + this.content.height / 2,
scaleX: 1,
scalY: 1,
...