Adam
Adam

Reputation: 29079

How to allow resizing while keeping aspect ratio in all cases?

I have a fabricImage and I want to allow resizing while keeping the aspect ratio intact.

By default, Fabric.js allows resizing from:

I tried setting lockScalingX = true and lockScalingY = true, but this completely prevents scaling, including corner scaling. Desired Behavior:

What I’ve tried:

How can I achieve this? Any help would be greatly appreciated!

Upvotes: 0

Views: 27

Answers (2)

DocAmz
DocAmz

Reputation: 106

Create custom controls with controlled scaling :

    fabric.FabricObject.prototype.controls = customControls();

Then make each controls individualy:

Action handler scalingEqually doc

const scaleEquallyControl = {
    cursorStyleHandler: fabric.controlsUtils.scaleCursorStyleHandler,
    actionHandler: fabric.controlsUtils.scalingEqually,
    actionName: "scaling",
};

Define defaultControl() with scalingEqually action handler demo | doc

export const customControls = () => ({
    ml: new fabric.Control({
        x: -0.5,
        y: 0,
        ...scaleEquallyControl,
    }),

    mr: new fabric.Control({
        x: 0.5,
        y: 0,
        ...scaleEquallyControl,
    }),

    mb: new fabric.Control({
        x: 0,
        y: 0.5,
        ...scaleEquallyControl,
    }),

    mt: new fabric.Control({
        x: 0,
        y: -0.5,
        ...scaleEquallyControl,
    }),
    ...yourOtherControls
})

Upvotes: 0

Muhammad Athar
Muhammad Athar

Reputation: 23

Set the centeredScaling property of the fabric.Object.prototype to true.

  fabric.Object.prototype.centeredScaling = true;

This will ensure that all objects created using Fabric.js will have centered scaling enabled by default.

You can check Vue FabricJs Starter kit for basic structure initialization.

Upvotes: 0

Related Questions