在fabric.js中围绕另一个对象旋转另一个独立对象

时间:2017-11-11 00:39:30

标签: javascript rotation fabricjs

请参阅以下小提琴:https://jsfiddle.net/logie17/r5zptv4o/

我正在尝试做的是在旋转对象B时围绕对象B旋转对象A.我的旋转功能如下所示:

function rotate() {
  let obj = boundingBox;
  obj.setCoords();
  let angle = fabric.util.degreesToRadians(obj.getAngle());
  let center = obj.getCenterPoint();
  let origin = new fabric.Point(center.x, center.y);
  let newCoords = fabric.util.rotatePoint(movingBox.getCenterPoint(),origin,angle);
  movingBox.set({ left: newCoords.x, top: newCoords.y }).setCoords();
}

但是从小提琴中可以看出,物体A旋转得非常快。我想保持旋转速度与旋转对象B相同。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

我能够解决这个问题,我需要保存objectA坐标的状态和角度变化的delta。以下是一个工作示例的演示:https://jsfiddle.net/logie17/r5zptv4o/10/

canvas.on("object:rotating", function(options){
  rotate();
});

let previousAngle = null;
let origX = movingBox.getCenterPoint().x;
let origY = movingBox.getCenterPoint().y;
let line;

function rotate() {
  let obj = boundingBox;

  origX = movingBox.getCenterPoint().x;
  origY = movingBox.getCenterPoint().y;
  let topLeftPoint = new fabric.Point(origX, origY);

  if (!previousAngle) {
    previousAngle = boundingBox.getAngle();
  }
  let angle = fabric.util.degreesToRadians(boundingBox.getAngle() - previousAngle);
  previousAngle = boundingBox.getAngle();
  let center = obj.getCenterPoint();
  let origin = new fabric.Point(obj.left, obj.top);
  let newCoords = fabric.util.rotatePoint(topLeftPoint,origin,angle);

  if (line) {
    canvas.remove(line);
  }
  line = new fabric.Line([ newCoords.x, newCoords.y, origin.x, origin.y ], {
    fill: 'black',
    stroke: 'black',
    strokeWidth: 5,
    selectable: false
  });
  canvas.add(line);
  movingBox.set({ left: newCoords.x, top: newCoords.y }).setCoords();
}