import Konva from 'konva'; import { Render } from '../index'; import { Handler } from '../types'; import { BaseGraph, Circle, Rect, Line, Bezier, Curve } from '../graphs'; import { GraphDraw } from '../draws'; export class GraphHandlers implements Handler { static readonly NAME = 'GraphHandlers'; private render: Render; constructor(render: Render) { this.render = render; } graphing = false; // 新建图形中 currentGraph: BaseGraph | undefined; // 当前新建图形类型 /** * 获取鼠标位置,并处理为 相对大小 * @param attract 含磁贴计算 * @returns */ getStagePoint(attract = false) { const pos = this.render.stage.getPointerPosition(); if (pos) { const stageState = this.render.getStageState(); if (attract) { // 磁贴 const { pos: transformerPos } = this.render.attractTool.attractPoint(pos); return { x: this.render.toStageValue(transformerPos.x - stageState.x), y: this.render.toStageValue(transformerPos.y - stageState.y) }; } else { return { x: this.render.toStageValue(pos.x - stageState.x), y: this.render.toStageValue(pos.y - stageState.y) }; } } return null; } handlers = { stage: { mousedown: (e: Konva.KonvaEventObject) => { if (this.render.graphType) { // 选中图形类型,开始 if (e.target === this.render.stage) { this.graphing = true; this.render.selectionTool.selectingClear(); this.render.linkTool.selectingClear(); const point = this.getStagePoint(); if (point) { switch (this.render.graphType) { case "Circle": // 新建 圆/椭圆 实例 this.currentGraph = new Circle(this.render, point); break; case "Rect": // 新建 矩形 实例 this.currentGraph = new Rect(this.render, point); break; case "Line": // 新建 直线、折线 this.currentGraph = new Line(this.render, point); break; case "Curve": // 新建 曲线 this.currentGraph = new Curve(this.render, point); break; case "Bezier": // 新建 贝赛尔曲线 this.currentGraph = new Bezier(this.render, point); break; default: break; } // 初始化设置信息 if (this.currentGraph) { const temSetting = this.render.getAssetSettings(this.currentGraph.group); this.render.setAssetSettings( this.currentGraph.group, { ...temSetting, stroke: temSetting.stroke || "#000000", strokeWidth: temSetting.strokeWidth || 1, fill: temSetting.fill || (["Circle", "Rect"].includes(this.render.graphType) ? "transparent" : "#000000"), }, false ); } } } } }, mousemove: () => { if (this.graphing) { if (this.currentGraph) { const pos = this.getStagePoint(true); if (pos) { // 新建并马上调整图形 this.currentGraph.drawMove(pos); } } } }, mouseup: () => { if (this.graphing) { if (this.currentGraph) { this.currentGraph.drawEnd(); // 调整结束 } this.graphing = false; // 调整结束 this.render.changeGraphType(); // 清空图形类型选择 this.render.attractTool.alignLinesClear(); // 对齐线清除 this.render.redraw([GraphDraw.NAME]); } } } } }