简体   繁体   中英

FabricJs: Keep Object Size fixed on Group Reszing

I am using FabricJS to create a group with two objects - light icon (svg) and shadow (triangle). Light Icon SVG I am importing as SVG and then setting scale like:

lightObj.scaleToWidth(24);
lightObj.scaleToHeight(24);

And then I am group the light icon svg object and shadow triangle object.

Next, I am trying to resize the group in order to resize the shadow object. And when I resize the group, I want to keep the size of light icon object as 24 ie same size as it was added. The light icon does not need to be scaled of resized. Here is my scaling function:

this.canvas.on('object:scaling', (e) => {
      if (!e) return;
      const group = e.target;
      const shadowObj = group._objects.find(x => x.type === 'shadow');
      const lightObj = group._objects.find(x => x.type === 'light');
      if(group.scaleX === group.scaleY) {
        //Uniform Scaling
        lightObj.scaleToWidth(24 / group.scaleX);
        lightObj.scaleToHeight(24 / group.scaleY);  
      } else {
        //Resizing
        if(group.scaleX > group.scaleY) {
          console.log("Horizontally")
          lightObj.scaleToWidth(24 / group.scaleX);
          lightObj.scaleToHeight(24);
        } else {
          console.log("Vertically")
          lightObj.scaleToHeight(24 / group.scaleY);
          lightObj.scaleToWidth(24);
        }
      }
      group.setCoords();
      this.canvas.renderAll();
    });

As you can see from above code, I have two part of IF condition. First is uniform scaling which works perfectly keeping my light obj size same as it was added. ELSE part is for RESIZING and inside that I have conditions for Horizontal and Vertical Resizing.

The problem I am facing is the light icon also gets resized when I resize the group horizontally or vertically. I am trying to keep the light icon size fixed. Any idea how can I achieve this? or What am I doing wrong here?

you can solve this problem by code scaling function like this:

    const group = e.target;
    const lightObj = group._objects.find(x => x.type === 'light');
    if (lightObj) {
      const scaleX = (lightObj.get('width') * 2) / group?.getScaledWidth();
      const scaleY = (lightObj.get('height') * 2) / group?.getScaledHeight();
      lightObj.set({ scaleX: scaleX, scaleY: scaleY });
    }

I have encountered the same scenario, it will work both on uniform scaling and horizontal or vertical scaling

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM