简体   繁体   中英

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();
}

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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM