import Konva from 'konva'; import { Render } from '../index'; import { AlignType } from '../types'; import { GraphDraw, LinkDraw, RulerDraw, PreviewDraw } from '../draws'; // 工具栏对齐 export class AlignTool { private render: Render; constructor(render: Render) { this.render = render; } getAlignRect(node: Konva.Node | Konva.Transformer) { const stageState = this.render.getStageState(); let width = 0, height = 0, x = 0, y = 0; const result = node.getClientRect(); // 转为 逻辑觉尺寸 [width, height, x, y] = [ this.render.toStageValue(result.width), this.render.toStageValue(result.height), this.render.toStageValue(result.x - stageState.x), this.render.toStageValue(result.y - stageState.y) ]; return { width, height, x, y }; } // 对齐参考点 getAlignPoints(node?: Konva.Node | Konva.Transformer): { [index: string]: number } { let width = 0, height = 0, x = 0, y = 0; if (node !== void 0) { // 选择器 / 基于节点 逻辑觉尺寸 const rect = this.getAlignRect(node); [width, height, x, y] = [rect.width, rect.height, rect.x, rect.y]; } else { // 默认为选择器 return this.getAlignPoints(this.render.transformer); } return { Middle: x + width / 2, Left: x, Right: x + width, Center: y + height / 2, Top: y, Bottom: y + height }; } align(type: AlignType, target?: Konva.Node) { // 对齐参考点(所有) const points = this.getAlignPoints(target); // 对齐参考点 const point = points[type]; // 需要移动的节点 const nodes = this.render.transformer.nodes().filter((node) => node !== target); // 移动逻辑 for (const node of nodes) { // 逻辑觉尺寸 const rect = this.getAlignRect(node); const [width, height, x, y] = [rect.width, rect.height, rect.x, rect.y]; switch (type) { case "Middle": case "Left": case "Right": { const cx = type === "Middle" ? x + width / 2 : type === "Left" ? x : x + width; node.x(node.x() + (point - cx)); } break; case "Center": case "Top": case "Bottom": { const cy = type === "Center" ? y + height / 2 : type === "Top" ? y : y + height; node.y(node.y() + (point - cy)); } break; } } // 更新历史 this.render.updateHistory(); // 重绘 this.render.redraw([ GraphDraw.NAME, LinkDraw.NAME, RulerDraw.NAME, PreviewDraw.NAME ]); } }