更改对象和错误的边界矩形的路径

时间:2018-02-02 01:29:43

标签: javascript canvas fabricjs

var canvas = new fabric.Canvas('canvas');
canvas.setWidth(500);
canvas.setHeight(500);
canvas.setBackgroundColor('#ccc');
canvas.allowTouchScrolling = true;

var line = new fabric.Path('M100,350 Q200,100 300,350', {
  fill: '',
  stroke: 'red',
  strokeWidth: 5,
  objectCaching: false
});
var circle = new fabric.Circle({
  radius: 15,
  fill: 'blue',
  lockScalingY: true,
  lockScalingX: true,
  left: 300,
  top: 350
});
canvas.add(line, circle);

canvas.on('object:moving', function(event) {
  var path = canvas.item(0);
  path.path[1][3] = event.target.left;
  path.path[1][4] = event.target.top;
  path.setCoords();
  canvas.calcOffset();
  canvas.renderAll();
});
<script src="//cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.20/fabric.js"></script>
<canvas id="canvas"></canvas>

this

当我移动圆圈时,有一条线的变化路径。在更改第I行的路径后,看到错误的边界矩形。 我怎么解决这个问题? 我可以删除行并再次创建,但也许有一种更简单的方法。

1 个答案:

答案 0 :(得分:1)

您实际上可以重新计算边界框,但您必须自己完成。

所以实际上很棘手,你需要从路径中删除当前的pathOffset,然后调用内部方法重新计算bbox。

它可以工作,但作为一种内部方法和一种不受支持的功能,它可以在将来进行更改。

&#13;
&#13;
var canvas = new fabric.Canvas('canvas');
canvas.setWidth(500);
canvas.setHeight(500);
canvas.setBackgroundColor('#ccc');
canvas.allowTouchScrolling = true;

var line = new fabric.Path('M100,350 Q200,100 300,350', {
  fill: '',
  stroke: 'red',
  strokeWidth: 5,
  objectCaching: false
});
var circle = new fabric.Circle({
  radius: 15,
  fill: 'blue',
  lockScalingY: true,
  lockScalingX: true,
  left: 300,
  top: 350
});
canvas.add(line, circle);

canvas.on('object:moving', function(event) {
  var path = canvas.item(0);
  path.path[1][3] = event.target.left;
  path.path[1][4] = event.target.top;
  path.pathOffset = null;
  path._setPositionDimensions({});
  path.setCoords();
  canvas.calcOffset();
  canvas.renderAll();
});
&#13;
<script src="//cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.20/fabric.js"></script>
<canvas id="canvas"></canvas>
&#13;
&#13;
&#13;