Search code examples
javascriptcanvashtml5-canvasfabricjs

Draw rectangle with aCoords tl, br corners instead of top, left in fabric.js?


So I wanted to draw rectangles on canvas based on coordinates received from an external system, which uses (x1,y1) (top-left) and (x2,y2) (bottom-right) coordinates to draw rectangle whereas in Fabric.js it's a bit different such as using the top and left properties, I tried to do it using aCoords and wrote this code:


  addRect() {
    let square = new fabric.Rect({
      stroke: 'yellow',
      noScaleCache: false,
      strokeWidth: 10,
      strokeUniform: true,
      fill: 'rgba(0,0,0,0.2)',
      flipX: true,
    });
    console.log(square.getCoords());

    square.set("aCoords", { tl: new fabric.Point(100, 2), br: new fabric.Point(1, 2), tr: new fabric.Point(1, 2), bl: new fabric.Point(1, 2) });

  
    this.canvas.add(square);
  }

This doesn't seem to work, what am I missing ?


Solution

  • Though from reading the API reference at fabricjs.com it's not certain but after digging through the code a little bit I'm almost sure aCoords just serves as a getter. So you can't modify a shapes appearance using this property.

    Instead you have update the top, left, width and height properties indivudually.

    Here's an example:

    (function() {
      var canvas = this.__canvas = new fabric.Canvas('c');
      fabric.Object.prototype.transparentCorners = false;
      let square = new fabric.Rect({
        stroke: 'yellow',
        noScaleCache: false,
        strokeWidth: 10,
        strokeUniform: true,
        fill: 'rgba(0,0,0,0.2)',
        flipX: true,
      });
    
      canvas.add(square);
    
      let x1 = 5;
      let y1 = 25;
      let x2 = 105;
      let y2 = 55;
    
      square.set("top", y1);
      square.set("left", x1);
      square.set("width", (x2 - x1));
      square.set("height", (y2 - y1));
    
    })();
    <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/4.2.0/fabric.min.js "></script>
    <canvas id="c"></canvas>