import Konva from 'konva'; import { GraphAnchor, Render, AssetInfoPoint, LineManualPoint } from '../types'; import { GraphDraw, LinkDraw, PreviewDraw } from '../draws'; import { BaseGraph } from './base-graph'; /** * 曲线 */ export class Curve extends BaseGraph { // 实现:更新 图形 的 调整点 的 锚点位置 static override updateAnchorShadows(graph: Konva.Group, anchorShadows: Konva.Circle[], shape?: Konva.Line): void { if (shape) { const points = shape.points(); for (const shadow of anchorShadows) { switch (shadow.attrs.adjustType) { case 'start': shadow.position({ x: points[0], y: points[1] }); break; case 'end': shadow.position({ x: points[points.length - 2], y: points[points.length - 1] }); break; } } } } // 实现:更新 图形 的 连接点 的 锚点位置 static override updateLinkAnchorShadows(graph: Konva.Group, linkAnchorShadows: Konva.Circle[], shape?: Konva.Line): void { if (shape) { const points = shape.points(); for (const shadow of linkAnchorShadows) { switch (shadow.attrs.alias) { case 'start': shadow.position({ x: points[0], y: points[1] }); break; case 'end': shadow.position({ x: points[points.length - 2], y: points[points.length - 1] }); break; } } } } static calculateAngle(sideA: number, sideB: number) { if (!isNaN(sideA) && !isNaN(sideB)) { const angleInRadians = Math.atan2(sideA, sideB); const angleInDegrees = angleInRadians * (180 / Math.PI); return angleInDegrees; } return 0; } // 实现:生成 调整点 static override createAnchorShapes( render: Render, graph: Konva.Group, anchorAndShadows: { anchor: GraphAnchor; anchorShadow: Konva.Circle; shape?: Konva.Shape; }[], // eslint-disable-next-line adjustAnchor?: GraphAnchor ): { anchorAndShadows: { anchor: GraphAnchor; anchorShadow: Konva.Circle; shape?: Konva.Shape | undefined; }[] } { const stageState = render.getStageState(); const graphShape = graph.findOne('.graph') as Konva.Line; if (graphShape) { const points = graphShape.points(); for (const anchorAndShadow of anchorAndShadows) { let rotate = 0; const { anchor, anchorShadow } = anchorAndShadow; const x = render.toStageValue(anchorShadow.getAbsolutePosition().x - stageState.x), y = render.toStageValue(anchorShadow.getAbsolutePosition().y - stageState.y); if (anchor.adjustType === 'manual') { const anchorShape = new Konva.Circle({ name: 'anchor', anchor: anchor, fill: anchor.adjusted ? `rgba(0,0,0,0.4)` : `rgba(0,0,255,0.4)`, radius: render.toStageValue(5), strokeWidth: 0, x: x, y: y, rotation: graph.getAbsoluteRotation(), visible: graph.attrs.adjusting || graph.attrs.hover === true }); anchorShape.on('mouseenter', () => { document.body.style.cursor = 'move'; graph.setAttr('hover', true); graph.setAttr('hoverAnchor', true); }); anchorShape.on('mouseleave', () => { document.body.style.cursor = anchorShape.attrs.adjusting ? 'move' : 'default'; graph.setAttr('hover', false); graph.setAttr('hoverAnchor', false); render.redraw([GraphDraw.NAME]); }); anchorAndShadow.shape = anchorShape; } else { if (anchor.adjustType === 'start') { rotate = Curve.calculateAngle(points[2] - points[0], points[3] - points[1]); } else if (anchor.adjustType === 'end') { rotate = Curve.calculateAngle(points[points.length - 2] - points[points.length - 4], points[points.length - 1] - points[points.length - 3]); } const cos = Math.cos((rotate * Math.PI) / 180); const sin = Math.sin((rotate * Math.PI) / 180); const offset = render.toStageValue(render.pointSize - 20); const offsetX = offset * sin; const offsetY = offset * cos; const anchorShape = new Konva.Circle({ name: 'anchor', anchor: anchor, fill: `rgba(0,0,255,0.4)`, radius: render.toStageValue(5), strokeWidth: 0, x: x, y: y, offsetX: anchor.adjustType === 'start' ? offsetX : anchor.adjustType === 'end' ? -offsetX : 0, offsetY: anchor.adjustType === 'start' ? offsetY : anchor.adjustType === 'end' ? -offsetY : 0, rotation: graph.getAbsoluteRotation(), visible: graph.attrs.adjusting || graph.attrs.hover === true }); anchorShape.on('mouseenter', () => { document.body.style.cursor = 'move'; graph.setAttr('hover', true); graph.setAttr('hoverAnchor', true); }); anchorShape.on('mouseleave', () => { document.body.style.cursor = anchorShape.attrs.adjusting ? 'move' : 'default'; graph.setAttr('hover', false); graph.setAttr('hoverAnchor', false); render.redraw([GraphDraw.NAME]); }); anchorAndShadow.shape = anchorShape; } } } return { anchorAndShadows }; } /** * 矩阵变换:坐标系中的一个点,围绕着另外一个点进行旋转 * - - - - - - - - * |x`| |cos -sin| |x-a| |a| * | | = | | | | + * |y`| |sin cos| |y-b| |b| * - - - - - - - - * @param x 目标节点坐标 x * @param y 目标节点坐标 y * @param centerX 围绕的点坐标 x * @param centerY 围绕的点坐标 y * @param angle 旋转角度 * @returns */ static rotatePoint(x: number, y: number, centerX: number, centerY: number, angle: number) { // 将角度转换为弧度 const radians = (angle * Math.PI) / 180; // 计算旋转后的坐标 const newX = Math.cos(radians) * (x - centerX) - Math.sin(radians) * (y - centerY) + centerX; const newY = Math.sin(radians) * (x - centerX) + Math.cos(radians) * (y - centerY) + centerY; return { x: newX, y: newY }; } // 实现:调整 图形 static override adjust( render: Render, graph: Konva.Group, graphSnap: Konva.Group, adjustShape: Konva.Shape, anchorAndShadows: { anchor: GraphAnchor; anchorShadow: Konva.Circle; shape?: Konva.Shape | undefined; }[], startPoint: Konva.Vector2d, endPoint: Konva.Vector2d, hoverRect?: Konva.Rect ) { // 目标 曲线 const line = graph.findOne('.graph') as Konva.Line; const lineSnap = graphSnap.findOne('.graph') as Konva.Line; const anchors = (graph.find('.anchor') ?? []) as Konva.Circle[]; const anchorsSnap = (graphSnap.find('.anchor') ?? []) as Konva.Circle[]; const linkAnchors = (graph.find('.link-anchor') ?? []) as Konva.Circle[]; if (line && lineSnap) { const stageState = render.getStageState(); { const [graphRotation, adjustType, ex, ey] = [ Math.round(graph.rotation()), adjustShape.attrs.anchor?.adjustType, endPoint.x, endPoint.y ]; const { x: cx, y: cy, width: cw, height: ch } = graphSnap.getClientRect(); const { x, y } = graph.position(); const [centerX, centerY] = [cx + cw / 2, cy + ch / 2]; const { x: sx, y: sy } = Curve.rotatePoint(ex, ey, centerX, centerY, -graphRotation); const { x: rx, y: ry } = Curve.rotatePoint(x, y, centerX, centerY, -graphRotation); const points = line.points(); const manualPoints = (line.attrs.manualPoints ?? []) as LineManualPoint[]; if (adjustType === 'manual') { if (adjustShape.attrs.anchor?.manualIndex !== void 0) { const index = adjustShape.attrs.anchor?.adjusted ? adjustShape.attrs.anchor?.manualIndex : adjustShape.attrs.anchor?.manualIndex + 1; const manualPointIndex = manualPoints.findIndex((o) => o.index === index); if (manualPointIndex > -1) { manualPoints[manualPointIndex].x = (sx - rx) / graph.scaleX(); manualPoints[manualPointIndex].y = (sy - ry) / graph.scaleY(); } const linkPoints = [ [points[0], points[1]], ...manualPoints.sort((a, b) => a.index - b.index).map((o) => [o.x, o.y]), [points[points.length - 2], points[points.length - 1]] ]; line.setAttr('manualPoints', manualPoints); line.points(linkPoints.flat()); const adjustAnchorShadow = anchors.find((o) => o.attrs.adjustType === 'manual' && o.attrs.manualIndex === index); if (adjustAnchorShadow) { adjustAnchorShadow.position({ x: (sx - rx) / graph.scaleX(), y: (sy - ry) / graph.scaleY() }); } } } else { const anchor = anchors.find((o) => o.attrs.adjustType === adjustType); const anchorShadow = anchorsSnap.find((o) => o.attrs.adjustType === adjustType); if (anchor && anchorShadow) { const linkPoints = [ [points[0], points[1]], ...manualPoints.sort((a, b) => a.index - b.index).map((o) => [o.x, o.y]), [points[points.length - 2], points[points.length - 1]] ]; switch (adjustType) { case 'start': linkPoints[0] = [(sx - rx) / graph.scaleX(), (sy - ry) / graph.scaleY()]; line.points(linkPoints.flat()); break; case 'end': linkPoints[linkPoints.length - 1] = [(sx - rx) / graph.scaleX(), (sy - ry) / graph.scaleY()]; line.points(linkPoints.flat()); break; } } } } Curve.updateAnchor(render, graph); Curve.updateAnchorShadows(graph, anchors, line); Curve.updateLinkAnchorShadows(graph, linkAnchors, line); for (const anchor of anchors) { for (const { shape } of anchorAndShadows) { if (shape) { if (shape.attrs.anchor?.adjustType === anchor.attrs.adjustType) { const anchorShadow = graph.find(`.anchor`).find((o) => o.attrs.adjustType === anchor.attrs.adjustType); if (anchorShadow) { shape.position({ x: render.toStageValue(anchorShadow.getAbsolutePosition().x - stageState.x), y: render.toStageValue(anchorShadow.getAbsolutePosition().y - stageState.y) }); shape.rotation(graph.getAbsoluteRotation()); } } } } } render.redraw([GraphDraw.NAME, LinkDraw.NAME, PreviewDraw.NAME]); } const allXs = line.points().reduce((arr, item, idx) => { if (idx % 2 === 0) arr.push(item); return arr; }, [] as number[]); const allYs = line.points().reduce((arr, item, idx) => { if (idx % 2 === 1) arr.push(item); return arr; }, [] as number[]); const minX = Math.min(...allXs); const maxX = Math.max(...allXs); const minY = Math.min(...allYs); const maxY = Math.max(...allYs); BaseGraph.adjust( render, graph, graphSnap, adjustShape, anchorAndShadows, startPoint, endPoint, hoverRect, { width: maxX - minX, height: maxY - minY }, { x: minX, y: minY } ); } /** * 提供给 GraphDraw draw 使用 */ static override draw(graph: Konva.Group, render: Render, adjustAnchor?: GraphAnchor) { const anchors = (graph.attrs.anchors ?? []) as (GraphAnchor & { manualIndex?: number; adjusted?: boolean })[]; const anchorShapes = graph.find(`.anchor`); const anchorAndShadows = anchors .map((anchor) => ({ anchor, anchorShadow: anchorShapes.find((shape) => shape.attrs.adjustType === anchor.adjustType && shape.attrs.manualIndex === anchor.manualIndex) as Konva.Circle })) .filter((o) => o.anchorShadow !== void 0); return Curve.createAnchorShapes(render, graph, anchorAndShadows, adjustAnchor); } /** * 默认图形大小 */ static size = 100; /** * 曲线 对应的 Konva 实例 */ private line: Konva.Line; constructor(render: Render, dropPoint: Konva.Vector2d) { super(render, dropPoint, { type: "Curve", anchors: [{ adjustType: 'start' }, { adjustType: 'end' }].map((o) => ({ adjustType: o.adjustType })), linkAnchors: [ { x: 0, y: 0, alias: 'start' }, { x: 0, y: 0, alias: 'end' } ] as AssetInfoPoint[] }); this.line = new Konva.Arrow({ name: 'graph', x: 0, y: 0, stroke: "#000000", strokeWidth: 1, fill: "#000000", points: [], pointerAtBeginning: false, pointerAtEnding: false, tension: 0 }); // 给予 1 像素,防止导出图片 toDataURL 失败 this.group.size({ width: 1, height: 1 }); this.group.add(this.line); this.group.position(this.dropPoint); // 鼠标按下位置 作为起点 } // 实现:拖动进行时 override drawMove(point: Konva.Vector2d): void { const offsetX = point.x - this.dropPoint.x, offsetY = point.y - this.dropPoint.y; // 起点、终点 const linkPoints = [ [this.line.x(), this.line.y()], [this.line.x() + offsetX, this.line.y() + offsetY] ]; // 曲线 路径 this.line.points(linkPoints.flat()); // 更新 图形 的 调整点 的 锚点位置 Curve.updateAnchorShadows(this.group, this.anchorShadows, this.line); // 更新 图形 的 连接点 的 锚点位置 Curve.updateLinkAnchorShadows(this.group, this.linkAnchorShadows, this.line); this.render.redraw([GraphDraw.NAME, LinkDraw.NAME, PreviewDraw.NAME]); } // 实现:拖动结束 override drawEnd(): void { if (this.line.width() <= 10 && this.line.height() <= 10) { const width = Curve.size, height = width; const linkPoints = [ [this.line.x(), this.line.y()], [this.line.x() + width, this.line.y() + height] ]; this.line.points(linkPoints.flat()); } Curve.updateAnchor(this.render, this.group); Curve.updateAnchorShadows(this.group, this.anchorShadows, this.line); Curve.updateLinkAnchorShadows(this.group, this.linkAnchorShadows, this.line); const size = {// 扣除多余的间隙 width: this.line.size().width - 10, height: this.line.size().height - 10 }; this.group.size(size); // 更新大小 this.render.attractTool.alignLinesClear(); // 对齐线清除 this.render.updateHistory(); // 更新历史 this.render.redraw([GraphDraw.NAME, LinkDraw.NAME, PreviewDraw.NAME]); super.drawEnd(size, { x: Math.min(...this.line.points().reduce((arr, item, idx) => { if (idx % 2 === 0) arr.push(item); return arr; }, [] as number[])), y: Math.min(...this.line.points().reduce((arr, item, idx) => { if (idx % 2 === 1) arr.push(item); return arr; }, [] as number[])) }); } /** * 更新 调整点(拐点) * @param render * @param graph */ static updateAnchor(render: Render, graph: Konva.Group) { const anchors = graph.attrs.anchors ?? []; const anchorShadows = graph.find('.anchor') ?? []; const shape = graph.findOne('.graph') as Konva.Line; if (shape) { let manualPoints = (shape.attrs.manualPoints ?? []) as LineManualPoint[]; const points = shape.points(); const linkPoints = [ [points[0], points[1]], ...manualPoints.sort((a, b) => a.index - b.index).map((o) => [o.x, o.y]), [points[points.length - 2], points[points.length - 1]] ]; // 清空 调整点(拐点),保留 start end anchors.splice(2); const shadows = anchorShadows.splice(2); for (const shadow of shadows) { shadow.remove(); shadow.destroy(); } manualPoints = []; for (let i = linkPoints.length - 1; i > 0; i--) { linkPoints.splice(i, 0, []); } for (let i = 1; i < linkPoints.length - 1; i++) { const anchor = { type: graph.attrs.graphType, adjustType: 'manual', name: 'anchor', groupId: graph.id(), manualIndex: i, adjusted: false }; if (linkPoints[i].length === 0) { anchor.adjusted = false; const prev = linkPoints[i - 1]; const next = linkPoints[i + 1]; const circle = new Konva.Circle({ adjustType: anchor.adjustType, anchorType: anchor.type, name: anchor.name, manualIndex: anchor.manualIndex, radius: 0, x: (prev[0] + next[0]) / 2, y: (prev[1] + next[1]) / 2, anchor }); graph.add(circle); } else { anchor.adjusted = true; const circle = new Konva.Circle({ adjustType: anchor.adjustType, anchorType: anchor.type, name: anchor.name, manualIndex: anchor.manualIndex, adjusted: true, radius: 0, x: linkPoints[i][0], y: linkPoints[i][1], anchor }); graph.add(circle); manualPoints.push({ x: linkPoints[i][0], y: linkPoints[i][1], index: anchor.manualIndex }); } anchors.push(anchor); } shape.setAttr('manualPoints', manualPoints); graph.setAttr('anchors', anchors); } } /** * 调整之前 */ static adjustStart( render: Render, graph: Konva.Group, adjustAnchor: GraphAnchor & { manualIndex?: number; adjusted?: boolean }, endPoint: Konva.Vector2d ) { const { x: gx, y: gy } = graph.position(); const shape = graph.findOne('.graph') as Konva.Line; if (shape && typeof adjustAnchor.manualIndex === 'number') { const manualPoints = (shape.attrs.manualPoints ?? []) as LineManualPoint[]; if (adjustAnchor.adjusted) { } else { manualPoints.push({ x: endPoint.x - gx, y: endPoint.y - gy, index: adjustAnchor.manualIndex }); shape.setAttr('manualPoints', manualPoints); } Curve.updateAnchor(render, graph); } } }