Search code examples
javascriptcanvasfabricjs

Offset issues images when inside group (scaleToWidth)


I'm experiencing an issue when scaling an image inside a group the offset of the image changes. The group consists of a background (Rect) and an image. When scaling the group the offset if the image becomes different. Expected is that the offset remains the same as the background.

I'm using Fabric 4.0.0-beta.6

enter image description here

const canvas = new fabric.Canvas('canvas');
canvas.setWidth(document.body.clientWidth);
canvas.setHeight(document.body.clientHeight);

const bg = new fabric.Rect({
  width: 100,
  height: 100,
  fill: 'red',
});

fabric.Image.fromURL("https://dummyimage.com/300x150/000/fff", function(img) {

  img.scaleToWidth(bg.width)
  const post = new fabric.Group([bg, img], {
    left: 100,
    top: 100,
  });

  post.scaleToWidth(400);
  canvas.add(post);
  canvas.renderAll();
});

https://jsbin.com/migogekoxu/1/edit?html,css,js,output


Solution

  • Setting the strokeWidth property of the background element to 0 fixed the offset for me.

    const canvas = new fabric.Canvas('canvas');
    canvas.setWidth(document.body.clientWidth);
    canvas.setHeight(document.body.clientHeight);
    
    const bg = new fabric.Rect({
      width: 100,
      height: 100,
      fill: 'red',
      strokeWidth: 0, //<---
    });
    
    fabric.Image.fromURL("https://dummyimage.com/300x150/000/fff", function(img) {
    
      img.scaleToWidth(bg.width)
      const post = new fabric.Group([bg, img], {
        left: 100,
        top: 100,
      });
    
      post.scaleToWidth(400);
      canvas.add(post);
      canvas.renderAll();
    });
    <canvas id="canvas"></canvas>
    <script src="https://cdn.jsdelivr.net/npm/fabric@4.0.0-beta.6-browser/dist/fabric.min.js"></script>