Search code examples
javascripthtmlcanvashtml5-canvasfabricjs

Shapes not rendering more than once in Fabricjs canvas?


I'm trying to make a button that adds shapes onto my FabricJS canvas but the shapes only appear once... ish. Every time I click on the button below, the rectangle's border gets thicker which I assume, means they're being added but whenever I go to drag the rectangle, it displays as only one.

How can I make the button add multiple rectangles to the canvas? (not all at once, after every click add 1)

My current code:

HTML:

<button onclick="addRectangle"></button>

JavaScript:

var rec = new fabric.Rect({
    top: 10,
    left: 10,
    width: 66,
    height: 35,
    fill: 'silver',
    stroke: 'black',
    strokeWidth: 1
});

function addRectangle() {
  c.add(rec);
  c.renderAll();
}

Solution

  • You're adding the same instance of fabric.Rect to the canvas, multiple times.

    When you call addRectangle() twice, two references to the same object end up in the internal _objects array - there's no safeguard to prevent that. During renderAll(), fabric.js iterates over the contents of this array and renders each element in it. That's why this Rect is being rendered twice.

    What you want to do is create a new Rect instance on each addRectangle() call:

    function createRect() {
      return new fabric.Rect({
        top: 10,
        left: 10,
        width: 66,
        height: 35,
        fill: "silver",
        stroke: "black",
        strokeWidth: 1
      });
    }
    
    function addRectangle() {
      var rect = createRect();
      c.add(rect);
      c.renderAll();
    }