简体   繁体   中英

Rotating another independent object around another object in fabric.js

Please see the following fiddle: https://jsfiddle.net/logie17/r5zptv4o/

What I'm trying to do is rotate object A around object B when rotating object B. My rotate function looks like this:

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

But as you can see from the fiddle, object A rotates very quickly. I would like to keep the speed of rotation the same as I rotate object B. Any help would be appreciated.

I was able to solve this, I needed to save the state of objectA's coordinates and the delta for the angle change. Here is a demonstration of a working example: 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();
}

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