Skip to content

Instantly share code, notes, and snippets.

@howtomakeaturn
Created November 21, 2020 15:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save howtomakeaturn/4024ffb925e25ee98e3c0e8c2b66f47d to your computer and use it in GitHub Desktop.
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
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);
});
@howtomakeaturn
Copy link
Author

The official doc is not very clear about how to extend textbox.

Here's the working example.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment