Goal: To center an object (horizontally and vertically) inside another object (rectangle or group) on canvas
via Fabric.js
or via Java
Figured it out.. Here's the StackBlitz: https://stackblitz.com/edit/angular-pg4fis
The trick was to first add the rectangle to a Fabric
group, like so:
var rect = new fabric.Rect({
left: 100,
top: 50,
width: 450,
height: 200,
fill: '#e3e3e3',
});
var rectGroup = new fabric.Group([rect], {
name: 'Rectangle',
});
this.canvas.add(rectGroup);
Then, I was able to establish the parent (group) element boundaries and use a variable scaling factor to set the image via Math
functionality:
fabric.Image.fromURL('https://angular.io/assets/images/logos/angular/logo-nav@2x.png', (img) => {
let bounds = rectGroup.getBoundingRect();
const scaleFactor = Math.min(
Math.min(1, bounds.width / img.width),
Math.min(1, bounds.height / img.height)
);
img.scale(scaleFactor);
img.set({
top: bounds.top + Math.max(bounds.height - img.height * scaleFactor, 0)/2,
left: bounds.left + Math.max(bounds.width - img.width * scaleFactor, 0)/2,
});
rectGroup.addWithUpdate(img);
this.canvas.renderAll();
});