在 Fabric.js 中通过 width/height 在另一个 canvas 对象中居中和缩放 canvas 对象

Centering and scaling canvas object inside another canvas object by width/height in Fabric.js

目标: 通过 Fabric.js 或 [=] 在 canvas 上使一个对象(水平和垂直)在另一个对象(矩形或组)内居中74=] 保持原始对象纵横比不变,但也不超过父对象 width/height 比例?

父对象(矩形或组)不会以 canvas 元素为中心。

这是我目前的代码: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),不仅新对象不会垂直居中,而且水平也不会居中。

我意识到我只是将内部图像对象的宽度声明为与父矩形边界宽度相同。

当前解法:

父矩形 width: 300height: 200:

父矩形 width: 300height: 50:

所需的解决方案:

父矩形 width: 300height: 200:

父矩形 width: 300height: 50:

有人可以帮忙吗?

想通了。这是 StackBlitz: https://stackblitz.com/edit/angular-pg4fis

诀窍是首先将矩形添加到 Fabric 组,如下所示:

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 功能设置图像:

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();
});