问题描述
目标:要通过Fabric.js
或Javascript将对象(水平或垂直)居中放置在canvas
上另一个对象(矩形或组)的内部,以保持原始对象长宽比不变,但不超过父对象的宽度/高度比例?
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?
父对象(矩形或组)不会居于canvas
元素的中心.
The parent object (rectangle or group) won't be centered on the canvas
element.
这是我到目前为止的代码: https://stackblitz.com/edit/angular-my8hky
Here's the code I have so far: https://stackblitz.com/edit/angular-my8hky
到目前为止,我的app.component.ts
:
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/logo-nav@2x.png', (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();
});
}
如果矩形对象的高度减小(例如,高度降低到50px
),则新对象不仅不会垂直居中,而且也不会水平居中.
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.
当前解决方案:
父矩形width: 300
和height: 200
:
父矩形width: 300
和height: 50
:
所需的解决方案:
父矩形width: 300
和height: 200
:
父矩形width: 300
和height: 50
:
有人可以协助吗?
推荐答案
解决了这个问题.这是StackBlitz: https://stackblitz.com/edit/angular-pg4fis
Figured it out.. Here's the StackBlitz:https://stackblitz.com/edit/angular-pg4fis
诀窍是首先将矩形添加到Fabric
组中,如下所示:
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);
然后,我能够建立父(组)元素边界,并使用可变比例因子通过Math
功能设置图像:
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();
});
这篇关于在Fabric.js中按宽度/高度在另一个画布对象内居中和缩放画布对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!