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

后端 未结 1 1637
感动是毒
感动是毒 2021-01-27 13:12

Goal: To center an object (horizontally and vertically) inside another object (rectangle or group) on canvas via Fabric.js or via Java

1条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-27 13:40

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

    0 讨论(0)
提交回复
热议问题