Text Container - Grouped
FabricJS
by Eugene Vilder
HTML
<script src="http://fabricjs.com/lib/fabric.js"></script>
<canvas id="paper" width="400" height="400" style="border:1px solid #ccc"></canvas>
JavaScript
// OVERRIDES ================================
const textAlignments = ['right', 'center', 'left'];
(function() {
fabric.TextFrame = fabric.util.createClass(fabric.Textbox, {
type: 'text-frame',
initialize: function(element, options) {
this.set({
autoHeight: options.autoHeight === undefined ? true : options.autoHeight,
});
this.callSuper('initialize', element, options);
this.set({
clipTo: function(ctx){
ctx.rect(-this.width / 2, -this.height / 2,this.width, this.height);
}.bind(this)
});
this.on('scaling', function(){
this.set({
scaleX: 1,
scaleY: 1,
clipTo: function(ctx){
ctx.rect(-this.width / 2, -this.height / 2,this.width, this.height);
}
});
});
this.on('modified', function(){
this.set({
clipTo: function(ctx){
ctx.rect(-this.width / 2, -this.height / 2,this.width, this.height);
}
});
});
},
calcTextHeight: function() {
if (!this.autoHeight) {
return this.height;
} else {
var lineHeight, height = 0;
for (var i = 0, len = this._textLines.length; i < len; i++) {
lineHeight = this.getHeightOfLine(i);
height += i === len - 1 ? lineHeight / this.lineHeight : lineHeight;
}
return height;
}
},
_getLineLeftOffset: function(lineIndex) {
var lineWidth = this.getLineWidth(lineIndex);
if (textAlignments[lineIndex] === "center") {
return (this.width - lineWidth) / 2;
}
if (textAlignments[lineIndex] === "right") {
return this.width - lineWidth;
}
if (textAlignments[lineIndex] === "justify-center" && this.isEndOfWrapping(lineIndex)) {
return (this.width - lineWidth) / 2;
}
if (textAlignments[lineIndex] === "justify-right"...