Created
November 21, 2020 15:43
-
-
Save howtomakeaturn/4024ffb925e25ee98e3c0e8c2b66f47d to your computer and use it in GitHub Desktop.
Fabric.js subclass working example, supporting clone - Textbox with background color and padding
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fabric.TextboxWithPadding = fabric.util.createClass(fabric.Textbox, { | |
type: 'textboxwithpadding', | |
toObject: function() { | |
return fabric.util.object.extend(this.callSuper('toObject'), { | |
backgroundColor: this.get('backgroundColor'), | |
padding: this.get('padding'), | |
}); | |
}, | |
_renderBackground: function(ctx) { | |
if (!this.backgroundColor) { | |
return; | |
} | |
var dim = this._getNonTransformedDimensions(); | |
ctx.fillStyle = this.backgroundColor; | |
ctx.fillRect( | |
-dim.x / 2 - this.padding, | |
-dim.y / 2 - this.padding, | |
dim.x + this.padding * 2, | |
dim.y + this.padding * 2 | |
); | |
// if there is background color no other shadows | |
// should be casted | |
this._removeShadow(ctx); | |
} | |
}); | |
fabric.TextboxWithPadding.fromObject = function(object, callback) { | |
return fabric.Object._fromObject('TextboxWithPadding', object, callback, 'text'); | |
}; | |
var t2 = new fabric.TextboxWithPadding('This is a Textbox', { | |
textAlign: 'center', | |
top: 200, | |
left: 100, | |
width: 400, | |
fontSize: 50, | |
fontWeight: 'bold', | |
fill: 'black', | |
stroke: 'white', | |
paintFirst: 'stroke', | |
strokeWidth: 3, | |
backgroundColor: 'yellow', | |
padding: 20, | |
}); | |
canvas.add(t2); | |
t2.clone((cloned) => { | |
cloned.set({ | |
left: cloned.left + 50, | |
top: cloned.top + 70, | |
}); | |
canvas.add(cloned); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The official doc is not very clear about how to extend textbox.
Here's the working example.