fabric.js围绕画布中心平滑旋转对象

时间:2018-08-28 02:14:13

标签: fabricjs

我尝试使用滑块平稳地围绕画布中心旋转对象, 我使用fabric.util.rotatePoint来找到新的中心点并设置新的角度,但是似乎不完全围绕中心点,并且对象位置正在跳跃。

https://jsfiddle.net/j0g1tLsb/26/

这是我的代码:

const canvas = new fabric.Canvas('c', { width: innerWidth, height: innerHeight });
canvas.controlsAboveOverlay = true;
canvas.preserveObjectStacking = true;

const rect = new fabric.Rect({
    width: 300,
  height: 150,
  left: 400,
  top: 400,
  fill: "lightgray",
    originX: 'center',
  originY: 'center'
});

const centerPoint = new fabric.Circle({ 
   originX: 'center',
   originY: 'center',
   top: innerHeight/2, 
   left: innerWidth/2,
   radius: 10, 
   fill: 'red',
   hasControls: false,
   selectable:false
});


const log = new fabric.Text('', {
    left: 30,
  top: 30,
  originX: 'left',
  originY: 'top',
  fontSize: 18,
  evented: false,
  selectable: false
});

canvas.add(rect, centerPoint, log);

document.getElementById('img-rotation').oninput = function() {
      rect.set('angle', this.value);

      var posNewCenter = fabric.util.rotatePoint(
                            rect.getCenterPoint(),
                            canvas.getVpCenter(),
                            fabric.util.degreesToRadians(this.value)
                        );

                        rect.set({
                            left: posNewCenter.x,
                            top: posNewCenter.y,
                            angle: this.value
                        });

      log.set('text', `angle: ${Math.round(rect.angle)} \nleft: ${rect.left} \ntop: ${rect.top}`);
      canvas.requestRenderAll();
    };


rect.on('modified', () => {
    log.set('text', `angle: ${Math.round(rect.angle)} \nleft: ${rect.left} \ntop: ${rect.top}`);
  canvas.renderAll();
});

1 个答案:

答案 0 :(得分:0)

您的问题是每次都从矩形获取中心点。您只需要从原始矩形位置设置新的Point。

var posNewCenter = fabric.util.rotatePoint(
    new fabric.Point(400, 400), //here is your mistake
    canvas.getVpCenter(),
    fabric.util.degreesToRadians(this.value)
);
rect.set({
    left: posNewCenter.x,
    top: posNewCenter.y,
    angle: this.value
});

工作fiddle

更新:

要修改矩形,您需要使用object:modified事件来重新分配topleft坐标。

首先声明顶部和左侧变量,并在矩形对象中使用它们:

let top = 400;
let left = 400;
const rect = new fabric.Rect({
  ...
  left: left,
  top: top,
  ...
  targetObj: 'rectangle' //you can use any value or ID, it's only for targeting purpose
});

然后,您需要检查何时修改对象。如果触发了事件,则检查它是否为矩形。

canvas.on('object:modified', (e) => {
    if (e.target.hasOwnProperty('targetObj') && e.target.targetObj === 'rectangle') {
    left = e.target.get('left');
    top = e.target.get('top');
  }
})

最后,在滑块的oninput事件中使用left和top变量:

var posNewCenter = fabric.util.rotatePoint(
    new fabric.Point(left, top),
    canvas.getVpCenter(),
    fabric.util.degreesToRadians(this.value)
);

正在更新fiddle