Skip to content

Instantly share code, notes, and snippets.

@howtomakeaturn
Last active September 13, 2023 04:23
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save howtomakeaturn/453753be4e415c20ab501b3a6259b87d to your computer and use it in GitHub Desktop.
Save howtomakeaturn/453753be4e415c20ab501b3a6259b87d to your computer and use it in GitHub Desktop.
Fabric.js subclass working example, supporting clone - LabeledRect
fabric.LabeledRect = fabric.util.createClass(fabric.Rect, {
type: 'labeledRect',
toObject: function() {
return fabric.util.object.extend(this.callSuper('toObject'), {
label: this.get('label')
});
},
_render: function(ctx) {
this.callSuper('_render', ctx);
ctx.font = '20px Helvetica';
ctx.fillStyle = '#333';
ctx.fillText(this.label, -this.width/2, -this.height/2 + 20);
}
});
fabric.LabeledRect.fromObject = function(object, callback) {
return fabric.Object._fromObject('LabeledRect', object, callback);
};
var labeledRect = new fabric.LabeledRect({
width: 100,
height: 50,
left: 600,
top: 100,
label: 'test',
fill: '#faa'
});
canvas.add(labeledRect);
labeledRect.clone((cloned) => {
cloned.set({
left: cloned.left + 50,
top: cloned.top + 70,
});
canvas.add(cloned);
});
@howtomakeaturn
Copy link
Author

The official example is not very correct.

Here's the working one.

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