Fabric.js偏移边界框问题

时间:2019-03-06 21:47:23

标签: javascript canvas html5-canvas fabricjs

我创建了一个动画,其中对象与fabric.js在一个组中。但是,当我将组添加到画布时,该组的边界框的位置向左偏移。关于如何解决这个问题有什么想法吗?

enter image description here

var canvas = new fabric.Canvas("canvas");
canvas.setWidth(554);
canvas.setHeight(312);

const rect = new fabric.Rect({
  width: 200,
  height: 50
})

const rect2 = new fabric.Rect({
  top: 50,
  width: 200,
  height: 50,
  fill: 'blue'
})

rect.animate({width: 300
             }, {
  duration: 300,
  onChange: canvas.renderAll.bind(canvas)
})

rect2.animate({width: 300}, {
  duration: 200,
  onChange: canvas.renderAll.bind(canvas)
})

const group  = new fabric.Group([rect, rect2], {
  top: 70,
  width: 300,
})

canvas.add(group)
canvas.setActiveObject(group)
canvas.renderAll()
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.5.0/fabric.min.js"></script>
  <canvas id="canvas" width="600" height="500" style="border:1px solid #ccc;z-index:99"></canvas>

1 个答案:

答案 0 :(得分:1)

addWithUpdateonComplete事件中使用animation更新组。

演示

const canvas = new fabric.Canvas("canvas");
canvas.setWidth(554);
canvas.setHeight(312);

const rect = new fabric.Rect({
  width: 200,
  height: 50
})

const rect2 = new fabric.Rect({
  top: 50,
  width: 200,
  height: 50,
  fill: 'blue'
})

rect.animate({
  width: 300
}, {
  duration: 300,
  onChange: canvas.renderAll.bind(canvas),
  onComplete: () => {
    group.addWithUpdate();
  }
})

rect2.animate({
  width: 300
}, {
  duration: 200,
  onChange: canvas.renderAll.bind(canvas),
  onComplete: () => {
    group.addWithUpdate();
  }
})

const group = new fabric.Group([rect, rect2], {
  top: 70
})

canvas.add(group)
canvas.setActiveObject(group)
canvas.renderAll()
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/2.6.0/fabric.js"></script>
<canvas id="canvas" width="600" height="500" style="border:1px solid #ccc;z-index:99"></canvas>