¿how to add lines in a rectangle fabricjs canvas

Viewed 29

How can you add lines inside a rectangle?

For example, if my rectangle has a height of 90 and I want to add 2 lines, it should appear like this, adj image enter link description here

but currently it comes out like this, adj image enter link description here

I have 2 functions, one that creates lines and the other that creates rectangles. then in the function of the rectangle I invoke the line, but they do not come out like the first image


  addLineToRectangle(){
    console.log("activeObject",this.rect.width);
    for (let i = 0; i < 2; i++) {
      let line = new fabric.Line([0, 100, 90, 100], {
        left: 1,
        top: 30 * i,
        stroke: 'red'
      });
      this.canvas?.add(line);
    }
  }

    
  addRect(){
    for (let i = 0; i < 1; i++) {
      this.rect = new fabric.Rect( {
        width: 90,
        height: 90,
        fill: 'transparent',
        stroke: 'blue',
        left: 1,
        top: 90 * i,
      });
      this.canvas?.add(this.rect);
      this.addLineToRectangle();
    }
  }

1 Answers

In FabricJS, Line has some interesting characteristics; you might consider switching to a Polyline. That said, here's a revised addLineToRectangle that works for me:

addLineToRectangle() {
  console.log("activeObject",this.rect.width);
  for (let i = 1; i <= 2; i++) {
    let line = new fabric.Line([0, 0, 90, 0], {
      left: 1,
      top: 30 * i,
      stroke: 'red',
    });
    canvas.add(line);
  }
}

Your top was starting at zero, and going up from there. I bumped your loop to start with 1, and also tweaked the y component of your line.

Related