用于实现元素 A 移动对应的元素 B 也需要进行相对位移,可以保持类似 左右 上下 之类的布局。
import { FitContentLayout, LayoutManager, Point } from 'fabric';
import { get } from 'lodash-es';
import type { FabricObject, LayoutContext } from 'fabric';
export class LogoAdjLayout extends LayoutManager {
relativePoint: Point = new Point(400, 400);
constructor() {
super(new FitContentLayout());
}
performLayout(context: LayoutContext) {
const { target: group } = context;
const { target } = get(context, 'e', {}) as { target?: FabricObject };
if (target) {
const targetId = target.get('id');
if (targetId === 'AAA') {
const bbb = group.getObjects().find((obj) => obj.get('id') === 'BBB');
if (bbb) {
const point = target.getCenterPoint();
const deltaX = -(point.x + target.width / 2 - this.relativePoint.x);
const deltaY = -(point.y + target.height / 2 - this.relativePoint.y);
bbb.set({ left: deltaX, top: deltaY });
}
} else if (targetId === 'BBB') {
const aaa = group.getObjects().find((obj) => obj.get('id') === 'AAA');
if (aaa) {
const point = target.getCenterPoint();
const deltaX = -(point.x + target.width / 2 - this.relativePoint.x);
const deltaY = -(point.y + target.height / 2 - this.relativePoint.y);
aaa.set({ left: deltaX, top: deltaY });
}
}
}
super.performLayout(context);
}
}