Last active
September 13, 2023 04:23
-
-
Save howtomakeaturn/453753be4e415c20ab501b3a6259b87d to your computer and use it in GitHub Desktop.
Fabric.js subclass working example, supporting clone - LabeledRect
This file contains hidden or 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.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); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The official example is not very correct.
Here's the working one.