在Fabric.js中按宽度/高度将画布对象居中并缩放到另一个画布对象中

目标:通过canvas或通过保留原始对象外观的Javascript将对象(水平或垂直)居于Fabric.js上另一个对象(矩形或组)内比例相同,但又不超过父对象的宽度/高度比例?

父对象(矩形或组)不会居于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

在Fabric.js中按宽度/高度将画布对象居中并缩放到另一个画布对象中

父矩形width: 300height: 50

在Fabric.js中按宽度/高度将画布对象居中并缩放到另一个画布对象中

所需的解决方案:

父矩形width: 300height: 200

在Fabric.js中按宽度/高度将画布对象居中并缩放到另一个画布对象中

父矩形width: 300height: 50

在Fabric.js中按宽度/高度将画布对象居中并缩放到另一个画布对象中

有人可以协助吗?

wocaonimasibusi 回答:在Fabric.js中按宽度/高度将画布对象居中并缩放到另一个画布对象中

弄清楚了..这是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,});

  rectGroup.addWithUpdate(img);
  this.canvas.renderAll();
});
本文链接:https://www.f2er.com/3156310.html

大家都在问