Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set the 4 corners X, Y coordinates value of a FabricJS image

I would like to set aCoords value of image. (Corner coordinates) Through setCoords it updates values however it does not change the position of the image.

        image?.set({
    'aCoords': {
        tl: new fabric.Point(0, 100),
        tr: new fabric.Point(0, 200),
        br: new fabric.Point(100, 200),
        bl: new fabric.Point(100, 200)
    }
})

     if(canvas) {
        console.log('render')
        image.setCoords()
        canvas.renderAll();
        canvas.requestRenderAll()
    }
like image 984
Elvin Avatar asked Oct 23 '25 03:10

Elvin


1 Answers

Here is an example, that you could also find in the discussion area on the repo:

https://github.com/fabricjs/fabric.js/discussions/6834

The solution is geometric only, nothing that is specifically of fabric.JS

// Canvas 2
var canvas2 = new fabric.Canvas('c2');

  const aCoords = {
      tl: new fabric.Point(0, 100),
      tr: new fabric.Point(0, 200),
      br: new fabric.Point(100, 200),
      bl: new fabric.Point(100, 100)
  }
  
  fabric.Image.fromURL('https://weeblytutorials.com/wp-content/uploads/2017/04/Weebly-blogs-example.png', img => {
    const width = img.width;
    const height = img.height;
    img.set({
      left: aCoords.tl.lerp(aCoords.br).x,
      top: aCoords.tl.lerp(aCoords.br).y,
      scaleX: (aCoords.tl.distanceFrom(aCoords.tr)) / width,
      scaleY: (aCoords.tl.distanceFrom(aCoords.bl)) / height,
      angle: fabric.util.radiansToDegrees(Math.atan2(aCoords.tr.y - aCoords.tl.y, aCoords.tr.x - aCoords.tl.x)),
      originX: 'center',
      originY: 'center',
    })
    canvas2.add(img);
  });
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/fabric.min.js"></script>
<canvas id="c2" width="400" height="400" >
like image 80
AndreaBogazzi Avatar answered Oct 25 '25 17:10

AndreaBogazzi