Canvas to Data URL
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="200" style="border:1px solid #ccc"></canvas>
<img id="img" />
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
});
},
_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,
angle: this.content.angle,
originX: 'center',
originY: 'center',
});
// img.scaleToWidth(this.content.width);
const patternSourceCanvas = new fabric.StaticCanvas();
patternSourceCanvas.setDimensions({
width: this.width,
height:...