Skip to content Skip to sidebar Skip to footer

Fabricjs: How To Auto-resize Image To Fit Group Or Rectangle Object?

Goal: I'm seeking to add an image to a FabricJS group or rectangle object, and for the image to maintain it's original aspect ratio and center fit it's parent width/height. I don't

Solution 1:

I figured it out, here's the Stackblitz: https://stackblitz.com/edit/angular-yoo8h5

First, I compared whether or not the rectangle aspect ratio is proportional to the image through an if/else statement which decides whether or not to initially scale the image to the rectangle width/height.

Then I set either the top or the left attribute of the image to the rectangle boundary point. Then calculating the center point of the rectangle and subtracting half of the image's boundary and lastly, setting the rectangle group object's clipPath to that of the rectangle, it worked!


fabric.Image.fromURL('https://placehold.it/888x500&text=16:9', (img) => {
    let bounds = rectGroup.getBoundingRect();

    if ((bounds.height / bounds.width) >= (img.height / img.width)) {
        img.scaleToHeight(bounds.height);
        img.set({
            top: bounds.top,
            left: (bounds.left + (bounds.width/2)) - (img.getBoundingRect().width/2)
        });
    }
    else {
        img.scaleToWidth(bounds.width);
        img.set({
            top: (bounds.top + (bounds.height/2)) - (img.getBoundingRect().height/2),
            left: bounds.left
        });
    }

    rectGroup.addWithUpdate(img);
    rectGroup.clipPath = rect;
    this.canvas.renderAll();
});

Solution 2:

A bit late here but chipping in in case this might be helpful.

You were heading in the right direction with Math.min, but you can use Math.max instead for the side with the larger group/image ratio to scale to the full length of the side. You can then set the x y origins to center.

fabric.Image.fromURL('https://placehold.it/888x500&text=16:9', (img) => {
    let bounds = rectGroup.getBoundingRect();

    const scaleFactor = Math.max(bounds.width / img.width, bounds.height / img.height);

    img.set({
      originX: 'center',
      originY: 'center',
      scaleX: scaleFactor,
      scaleY: scaleFactor
    });

    rectGroup.addWithUpdate(img);
    this.canvas.renderAll();
}

Post a Comment for "Fabricjs: How To Auto-resize Image To Fit Group Or Rectangle Object?"