Goal: To center an object (horizontally and vertically) inside another object (rectangle or group) on canvas
via Fabric.js
or via Javascript which keeps the original object aspect ratio the same, but also not exceed the parent object width/height proportions?
The parent object (rectangle or group) won't be centered on the canvas
element.
Here's the code I have so far: https://stackblitz.com/edit/angular-my8hky
My app.component.ts
so far:
canvas: fabric.Canvas;
ngOnInit() {
this.canvas = new fabric.Canvas('canvas');
var rect = new fabric.Rect({
left: 100,
top: 50,
width: 300,
height: 200,
fill: '#eee'
});
this.canvas.add(rect);
fabric.Image.fromURL('https://angular.io/assets/images/logos/angular/[email protected]', (img) => {
let bounds = rect.getBoundingRect();
let oImg = img.set({
left: bounds.left,
top: bounds.top,
width: rect.width
}).scale(1);
this.canvas.add(oImg).renderAll();
});
}
Not only is the new object not centered vertically, but also not centered horizontally if the rectangle object height is decreased (for example to 50px
in height).
I realize I'm only declaring the inner image object width to be the same as the parent rectangle boundary width.
Current solution:
Parent rectangle width: 300
and height: 200
:
Parent rectangle width: 300
and height: 50
:
Desired solution:
Parent rectangle width: 300
and height: 200
:
Parent rectangle width: 300
and height: 50
:
Can anyone assist?