结构 js 对象使用另一个对象进行管理



我的画布有两个对象。第一个是可选的真,第二个是可选的假。我希望通过第一个对象的操作来管理第二个对象。

如果第一个对象移动,则第二个对象需要沿同一方向移动。如果第一个旋转,则第二个在第二个的位置以相同的角度旋转。

我尝试将事件(移动,旋转)添加到第一个可选对象,然后从第一个对象获取所需的值并将其设置为第二个对象,但旋转无法正常工作。我的代码如下:

imageOne.on('rotating', function (evt) { imageThree.angle = imageOne.getAngle(); }); 

var canvas = new fabric.Canvas('c');
var evented = false;
var rect1 = new fabric.Rect({
  left: 50,
  top: 60,
  fill: 'blue',
  width: 150,
  height: 150,
});
var rect2 = new fabric.Rect({
  left: 210,
  top: 60,
  fill: 'magenta',
  width: 150,
  height: 150,
  selectable: false
});
canvas.add(rect1,rect2);
function rect1MouseDown(option){
 this.mousesDownLeft = this.left;
 this.mousesDownTop = this.top;
 this.rect2Left = rect2.left;
 this.rect2Top = rect2.top;
}
function rect1Move(option){
 rect2.left = this.rect2Left+ this.left - this.mousesDownLeft ;
 rect2.top = this.rect2Top+ this.top- this.mousesDownTop;
 rect2.setCoords();
}
function rect1Rotating(options){
 rect2.setAngle(this.angle);
}
register();
function register(){
 if(evented) return;
 rect1.on('moving', rect1Move);
 rect1.on('mousedown', rect1MouseDown);
 rect1.on('rotating', rect1Rotating);
 evented = true;
}
function unRegister(){
 rect1.off('moving');
 rect1.off('mousedown');
 rect2.on('rotating');
 evented = false;
}
canvas {
 border: blue dotted 2px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.19/fabric.min.js"></script>
<button onclick='register()'>Register Event</button>
<button onclick='unRegister()'>Unregister Event</button><br>
<canvas id="c" width="400" height="400"></canvas>

您可以使用版本 <1.7.19 的obj.setAngle()和版本 2 的 obj.rotate() 来设置对象的角度。

最新更新