Reputation: 21
I am working on a Fabric Grid using Fabric.js and I want to add the dimensions of the shape that is added on the canvas. The new Width and Height is defined but I will need to not only show the dimensions on the screen, but also get it updated when I resize the shape.
Below is the JS function, where newWidth
and newHeight
are defined:
function snapToGrid() {
let checkBox = document.getElementById("myCheck");
if (checkBox.checked == true) {
//snap only to the grid
const gridSize = 50;
c.on("object:moving", function (options) {
options.target.set({
left: Math.round(options.target.left / gridSize) * gridSize,
top: Math.round(options.target.top / gridSize) * gridSize,
});
});
c.on("object:modified", function (options) {
var newWidth =
Math.round(options.target.getWidth() / gridSize) * gridSize;
var newHeight =
Math.round(options.target.getHeight() / gridSize) * gridSize;
options.target.set({
width: newWidth,
height: newHeight,
scaleX: 1,
scaleY: 1,
});
});
} else {
c.off("object:modified");
c.off("object:moving");
}
}
I am new to Fabric.js and would appreciate if someone helped me on this. Please let me know if I'' have to share more details of the code.
Upvotes: 0
Views: 353
Reputation: 21
Okay so I've answered my own question, so if anyone needs it, here's the below code that would help to dynamically show your shape's width and height while altered.
function onObjectScaled(e){
var scaledObject = e.target;
var text = document.getElementById("text");
text.value = 'Width = '+scaledObject.getWidth() + ' Height = '+scaledObject.getHeight();
}
Upvotes: 0