简体   繁体   English

在 Fabricjs canvas 中,形状不会多次渲染?

[英]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.我正在尝试制作一个按钮,将形状添加到我的 FabricJS canvas 但形状只出现一次...... 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.每次单击下面的按钮时,矩形的边框都会变粗,我认为这意味着它们正在被添加,但是每当我用 go 拖动矩形时,它只会显示为一个。

How can I make the button add multiple rectangles to the canvas?如何使按钮向 canvas 添加多个矩形? (not all at once, after every click add 1) (不是一次全部,每次点击后添加1)

My current code:我当前的代码:

HTML: HTML:

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

JavaScript: 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.您将多次添加相同fabric.Rect实例到 canvas。

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.当您调用addRectangle()两次时,对同一 object 的两个引用最终会出现在内部_objects数组中 - 没有任何安全措施可以防止这种情况发生。 During renderAll() , fabric.js iterates over the contents of this array and renders each element in it.renderAll()期间,fabric.js 迭代这个数组的内容并渲染其中的每个元素。 That's why this Rect is being rendered twice.这就是为什么这个 Rect 被渲染两次的原因。

What you want to do is create a new Rect instance on each addRectangle() call:您要做的是在每个addRectangle()调用上创建一个新的Rect实例:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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