FenceEditor.vue 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708
  1. <template>
  2. <div id="editorMap" ref="mapRef"></div>
  3. </template>
  4. <script lang="ts" setup>
  5. import Konva from 'konva';
  6. import { ref, onMounted, onUnmounted } from 'vue';
  7. import { GROUP_NAME, POLYGON_NAME, Points, ToolObjectItem, toolObject } from './constants';
  8. import { ElMessage } from 'element-plus';
  9. import { getDefaultScale } from './utils';
  10. import { Group } from 'konva/lib/Group';
  11. const mapRef = ref<HTMLCanvasElement | null>(null);
  12. let currentTool: ToolObjectItem = toolObject[1];
  13. let isEdit = false;
  14. let stage: Konva.Stage | null = null;
  15. let layer: Konva.Layer | null = null;
  16. let currentDrawingShape: Konva.Group | null = null; //现在绘画的图形
  17. let polygonPoints: number[] = []; //存储绘画多边形各个顶点的数组
  18. let stageWidth = 0; //舞台宽
  19. let stageHeight = 0; //舞台高
  20. let scale = 1; //窗口变化的缩放比例
  21. let drawing = false; //一开始不能绘画
  22. let currentDel: Konva.Node | null = null; //删除对象
  23. onMounted(() => {
  24. initKonvaStage();
  25. //禁止浏览器右击菜单
  26. document.oncontextmenu = function () {
  27. return false;
  28. };
  29. });
  30. onUnmounted(() => {
  31. stage?.destroy();
  32. });
  33. /**
  34. *初始化konva舞台
  35. */
  36. function initKonvaStage() {
  37. //1实例化stage层
  38. stageWidth = mapRef.value?.clientWidth || 0;
  39. stageHeight = mapRef.value?.clientHeight || 0;
  40. console.log('stageWidth', stageWidth);
  41. stage = new Konva.Stage({
  42. container: 'editorMap',
  43. width: stageWidth,
  44. height: stageHeight,
  45. ignoreStroke: true,
  46. background: '#00ff00',
  47. });
  48. if (import.meta.env.MODE === 'development') {
  49. window.stage = stage;
  50. }
  51. setStageCursor('pointer');
  52. //2实例化layer层
  53. layer = new Konva.Layer();
  54. //3添加layer层
  55. stage?.add(layer);
  56. //给***舞台***绑定事件
  57. stageBindEvent();
  58. }
  59. /**
  60. * 舞台绑定的事件
  61. * @param vc_this
  62. */
  63. function stageBindEvent() {
  64. //鼠标按下
  65. stage?.on('mousedown', (e) => {
  66. //鼠标左键开始
  67. console.log('stage mousedown', e);
  68. if (!isEdit) return;
  69. if (e.evt.button == 0) {
  70. if (e.target === stage) {
  71. stageMousedown(currentTool!);
  72. return;
  73. }
  74. //图形起始点只能在图片层上
  75. // if (e.target === shape) {
  76. // //开始初始绘画
  77. // stageMousedown(currentTool!);
  78. // return;
  79. // }
  80. //允许后续点绘画在其他图形上
  81. if (drawing) {
  82. stageMousedown(currentTool!);
  83. return;
  84. }
  85. } else if (e.evt.button == 2) {
  86. // 如果polygonPoints为空,那么右击是没有反应的。
  87. console.log('mousedown 2');
  88. }
  89. });
  90. //鼠标移动
  91. stage?.on('mousemove', () => {
  92. if (!isEdit) return;
  93. if (currentTool && drawing) {
  94. //绘画中
  95. stageMousemove();
  96. }
  97. });
  98. //鼠标放开
  99. stage?.on('mouseup', (e: Konva.KonvaEventObject<any>) => {
  100. if (!isEdit) return;
  101. if (e.evt.button == 0) {
  102. if (drawing) {
  103. stageMouseup(e);
  104. }
  105. } else if (e.evt.button == 2) {
  106. if (polygonPoints.length != 0) {
  107. stageMouseup(e);
  108. }
  109. }
  110. });
  111. // //鼠标滚轮事件取消
  112. //舞台快捷键
  113. var container = stage?.container();
  114. if (!container) return;
  115. container.tabIndex = 1;
  116. container?.focus();
  117. container?.addEventListener('keydown', (e) => {
  118. if (!isEdit) return;
  119. //删除的快捷键
  120. if (e.keyCode === 46) {
  121. removeCurrent();
  122. }
  123. if (container) {
  124. container.style.cursor = 'crosshair';
  125. }
  126. e.preventDefault();
  127. layer?.draw();
  128. });
  129. }
  130. const getPolygonInGroup = (g: Konva.Group | null) => {
  131. if (!g) return;
  132. return g.findOne(POLYGON_NAME) as Konva.Line;
  133. };
  134. /** 设置当前选中的group */
  135. function setCurrentGroup(group: Konva.Group | null) {
  136. currentDrawingShape = group;
  137. setGroupActive(group);
  138. currentDel = group;
  139. }
  140. /**
  141. * 在舞台上鼠标点下发生的事件
  142. * @param currentTool 当前选择的工具
  143. * @param e 传入的event对象
  144. */
  145. function stageMousedown(currentTool: ToolObjectItem) {
  146. if (!isEdit) return;
  147. console.log('stagemousedown');
  148. //如果数组长度小于2,初始化多边形和顶点,使它们成为一组,否则什么都不做
  149. // 小于2说明一个点也没有,一个点的长度是2,所以要先创建group
  150. if (polygonPoints.length < 2) {
  151. //最好使用konva提供的鼠标xy点坐标
  152. var mousePos = stage?.getPointerPosition();
  153. console.log('mousePos', mousePos);
  154. if (!mousePos) return;
  155. //考虑鼠标缩放
  156. var x = (mousePos.x / scale - layer?.getAttr('x')) / getDefaultScale(layer?.scaleX()),
  157. y = (mousePos.y / scale - layer?.getAttr('y')) / getDefaultScale(layer?.scaleY());
  158. //拖拽组
  159. var group = new Konva.Group({
  160. name: currentTool.name + 'group',
  161. draggable: false,
  162. });
  163. polygonPoints = [x, y];
  164. //添加多边形的点
  165. drawCircle(x, y, group, polygonPoints);
  166. //绘画多边形
  167. drawPolygon(currentTool, polygonPoints, group);
  168. //添加多边形的边
  169. // drawLine(currentTool, polygonPoints, group);
  170. layer?.add(group);
  171. setCurrentGroup(group);
  172. currentDel = group;
  173. //使所有顶点在顶层显示
  174. stage?.find('Circle').forEach((element) => {
  175. element.moveToTop();
  176. });
  177. layer?.draw();
  178. } //多边形增加顶点
  179. else {
  180. //最好使用konva提供的鼠标xy点坐标
  181. var mousePos = stage?.getPointerPosition();
  182. if (!mousePos) return;
  183. //考虑鼠标缩放
  184. var x = (mousePos.x / scale - layer?.getAttr('x')) / getDefaultScale(layer?.scaleX()),
  185. y = (mousePos.y / scale - layer?.getAttr('y')) / getDefaultScale(layer?.scaleY());
  186. //group继续添加多边形的点
  187. drawCircle(x, y, currentDrawingShape!, polygonPoints);
  188. polygonPoints.push(x);
  189. polygonPoints.push(y);
  190. const polygon = getPolygonInGroup(currentDrawingShape);
  191. currentDel = currentDrawingShape;
  192. //绘画多边形
  193. polygon?.setAttr('points', polygonPoints);
  194. //group继续添加多边形的边
  195. //使所有顶点在顶层显示
  196. stage?.find('Circle').forEach((element) => {
  197. element.moveToTop();
  198. });
  199. layer?.draw();
  200. }
  201. drawing = true;
  202. }
  203. /**
  204. * 鼠标在舞台上移动事件
  205. * @param currentTool 当前选择的工具
  206. * @param e 传入的event对象
  207. */
  208. function stageMousemove() {
  209. if (!isEdit) return;
  210. const container = stage?.container();
  211. if (!container) return;
  212. container.style.cursor = 'crosshair';
  213. //多边形初始化后,如果数组长度大于2,鼠标移动时,实时更新下一个点
  214. if (polygonPoints.length >= 2) {
  215. var mousePos = stage?.getPointerPosition();
  216. if (!mousePos) return;
  217. var x = (mousePos.x / scale - layer?.getAttr('x')) / getDefaultScale(layer?.scaleX()),
  218. y = (mousePos.y / scale - layer?.getAttr('y')) / getDefaultScale(layer?.scaleY());
  219. var tempPoints = polygonPoints.concat([]);
  220. tempPoints.push(x);
  221. tempPoints.push(y);
  222. const polygon = getPolygonInGroup(currentDrawingShape);
  223. //更新多边形
  224. polygon?.setAttr('points', tempPoints);
  225. //使所有顶点在顶层显示
  226. stage?.find('Circle').forEach((element) => {
  227. element.moveToTop();
  228. });
  229. }
  230. layer?.draw();
  231. }
  232. /**
  233. * 鼠标在舞台弹起
  234. * @param currentTool 当前选择的工具
  235. * @param e 传入的event对象
  236. */
  237. function stageMouseup(e: Konva.KonvaEventObject<any>) {
  238. if (!isEdit) return;
  239. if (e.evt.button == 2) {
  240. if (polygonPoints.length != 0) {
  241. //最好使用konva提供的鼠标xy点坐标
  242. var mousePos = stage?.getPointerPosition();
  243. if (!mousePos) return;
  244. //考虑鼠标缩放
  245. var x = (mousePos.x / scale - layer?.getAttr('x')) / getDefaultScale(layer?.scaleX()),
  246. y = (mousePos.y / scale - layer?.getAttr('y')) / getDefaultScale(layer?.scaleY());
  247. //group继续添加多边形的点
  248. // 右击和左击都要添加一个点
  249. drawCircle(x, y, currentDrawingShape!, polygonPoints);
  250. polygonPoints.push(x);
  251. polygonPoints.push(y);
  252. const polygon = getPolygonInGroup(currentDrawingShape);
  253. //绘画多边形
  254. polygon?.setAttr('points', polygonPoints);
  255. //判断是否是只有两个点的多边形,如果起点和终点相同,不允许绘画
  256. if (polygon?.points().length == 2 || polygon?.points().length == 4) {
  257. drawing = false;
  258. currentDrawingShape?.destroy();
  259. polygonPoints = [];
  260. ElMessage({
  261. message: '顶点数必须大于2个!',
  262. type: 'warning',
  263. center: true,
  264. duration: 1000,
  265. });
  266. return;
  267. }
  268. //右键弹起
  269. polygonPoints = [];
  270. // 停止事件冒泡
  271. e.cancelBubble = true;
  272. // 停止画多边形
  273. drawing = false;
  274. }
  275. }
  276. //使所有顶点在顶层显示
  277. stage?.find('Circle').forEach((element) => {
  278. element.moveToTop();
  279. });
  280. layer?.draw();
  281. }
  282. /**
  283. * 多边形圆形
  284. * @param //x x坐标
  285. * @param //y y坐标
  286. */
  287. function drawCircle(x: number, y: number, group: Konva.Group, shapePoints: number[]) {
  288. const circle = new Konva.Circle({
  289. name: currentTool.name + 'circle',
  290. x: x,
  291. y: y,
  292. radius: 8 / scale / getDefaultScale(layer?.scaleX()),
  293. visible: true, //是否显示
  294. fill: currentTool.anchorColor,
  295. stroke: currentTool.anchorColor,
  296. draggable: false,
  297. strokeWidth: 0.5,
  298. strokeScaleEnabled: false,
  299. //增加点击区域
  300. hitStrokeWidth: 12 / scale / getDefaultScale(layer?.scaleX()),
  301. //设置拖动区域,不能超过舞台大小
  302. dragBoundFunc: function (pos) {
  303. //左上角
  304. if (pos.x < 0 && pos.y < 0) {
  305. return {
  306. x: 0,
  307. y: 0,
  308. };
  309. } //左侧
  310. else if (pos.x <= 0 && 0 <= pos.y && pos.y <= (stage?.height() ?? 0)) {
  311. return {
  312. x: 0,
  313. y: pos.y,
  314. };
  315. }
  316. //左下角
  317. else if (pos.x < 0 && pos.y > (stage?.height() ?? 0)) {
  318. return {
  319. x: 0,
  320. y: stage?.height(),
  321. };
  322. } //下侧
  323. else if (0 <= pos.x && pos.x <= (stage?.width() ?? 0) && pos.y > (stage?.height() ?? 0)) {
  324. return {
  325. x: pos.x,
  326. y: stage?.height(),
  327. };
  328. } //右下角
  329. else if (pos.x > (stage?.width() ?? 0) && pos.y > (stage?.height() ?? 0)) {
  330. return {
  331. x: stage?.width(),
  332. y: stage?.height(),
  333. };
  334. }
  335. //右侧
  336. else if (pos.x > (stage?.width() ?? 0) && 0 <= pos.y && pos.y <= (stage?.height() ?? 0)) {
  337. return {
  338. x: stage?.width(),
  339. y: pos.y,
  340. };
  341. }
  342. //右上角
  343. else if (pos.x > (stage?.width() ?? 0) && pos.y < 0) {
  344. return {
  345. x: stage?.width(),
  346. y: 0,
  347. };
  348. } //上侧
  349. else if (0 <= pos.x && pos.x <= (stage?.width() ?? 0) && pos.y < 0) {
  350. return {
  351. x: pos.x,
  352. y: 0,
  353. };
  354. }
  355. },
  356. });
  357. group.add(circle);
  358. let xChange: number, yChange: number;
  359. circle.on('mouseover', () => {
  360. const c = stage?.container();
  361. if (!c) return;
  362. c.style.cursor = 'pointer';
  363. });
  364. circle.on('mousedown', (e) => {
  365. if (!isEdit) return;
  366. console.log('circle,');
  367. if (!drawing) {
  368. circle.draggable(true);
  369. //将现在绘画的对象改为group
  370. setCurrentGroup(circle.getParent() as Konva.Group);
  371. } else {
  372. circle.draggable(false);
  373. }
  374. e.cancelBubble = true;
  375. });
  376. circle.on('mouseleave', () => {
  377. if (!isEdit) return;
  378. const c = stage?.container();
  379. if (!c) return;
  380. c.style.cursor = 'crosshair';
  381. });
  382. circle.on('dragstart', () => {
  383. if (!isEdit) return;
  384. switch (currentTool?.type) {
  385. case 'poly':
  386. //查找拖拽了多边形的哪个点
  387. for (var i = 0; i < shapePoints.length; i += 2) {
  388. if (
  389. circle.getAttr('x') == shapePoints[i] &&
  390. circle.getAttr('y') == shapePoints[i + 1]
  391. ) {
  392. xChange = i;
  393. yChange = i + 1;
  394. break;
  395. }
  396. }
  397. break;
  398. default:
  399. break;
  400. }
  401. });
  402. circle.on('dragmove', () => {
  403. if (!isEdit) return;
  404. switch (currentTool?.type) {
  405. case 'poly':
  406. var x = circle.x();
  407. var y = circle.y();
  408. //更改拖拽点的位置
  409. shapePoints[xChange] = x;
  410. shapePoints[yChange] = y;
  411. break;
  412. default:
  413. break;
  414. }
  415. });
  416. circle.on('dragend', (e) => {
  417. if (!isEdit) return;
  418. switch (currentTool?.type) {
  419. case 'poly':
  420. //使所有顶点在顶层显示
  421. stage?.find('Circle').forEach((element) => {
  422. element.moveToTop();
  423. });
  424. circle.draggable(false);
  425. break;
  426. default:
  427. break;
  428. }
  429. // ElMessage({
  430. // message: '修改成功!',
  431. // type: 'success',
  432. // center: true,
  433. // duration: 1000,
  434. // });
  435. e.cancelBubble = true;
  436. });
  437. return circle;
  438. }
  439. function setStageCursor(cursor: string) {
  440. const c = stage?.container();
  441. if (c) {
  442. c.style.cursor = cursor;
  443. }
  444. }
  445. /** 设置当前的group为active */
  446. function setGroupActive(activeGroup: Group | null) {
  447. const groups = stage?.find(GROUP_NAME) as Konva.Group[];
  448. if (!groups) return;
  449. /** 将其他组的线条设为非高亮 */
  450. groups.forEach((g: Konva.Group) => {
  451. if (g === activeGroup) return;
  452. g.find(POLYGON_NAME).forEach((line) => {
  453. (line as Konva.Line).stroke(currentTool?.color!);
  454. });
  455. g.find('Circle').forEach((circle) => {
  456. (circle as Konva.Circle).hide();
  457. });
  458. });
  459. if (!activeGroup) return;
  460. const thisLine = activeGroup.findOne(POLYGON_NAME) as Konva.Line;
  461. if (thisLine) {
  462. thisLine.stroke(currentTool.activeColor);
  463. }
  464. const thisCircles = activeGroup.find('Circle') as Konva.Circle[];
  465. if (thisCircles) {
  466. thisCircles.forEach((circle) => {
  467. (circle as Konva.Circle).show();
  468. });
  469. }
  470. layer?.draw();
  471. }
  472. /**
  473. *多边形
  474. @param currentTool
  475. * @param points 多边形绘画的各个顶点,类型数组
  476. */
  477. function drawPolygon(currentTool: ToolObjectItem, points: number[], group: Konva.Group) {
  478. let poly = new Konva.Line({
  479. name: currentTool.name + 'poly',
  480. points: points,
  481. /* fill: currentTool.color, */
  482. stroke: currentTool.color,
  483. strokeWidth: 3,
  484. draggable: false,
  485. opacity: 1,
  486. lineCap: 'round',
  487. lineJoin: 'round',
  488. closed: true,
  489. strokeScaleEnabled: false,
  490. });
  491. group.add(poly);
  492. setCurrentGroup(group);
  493. const pParent = group;
  494. pParent?.on('mouseleave', () => {
  495. if (!isEdit) return;
  496. const c = stage?.container();
  497. if (c) {
  498. c.style.cursor = 'crosshair';
  499. }
  500. });
  501. pParent?.on('mousedown', (e) => {
  502. if (!isEdit) return;
  503. console.log('group mouse down', e);
  504. if (e.evt.button == 0) {
  505. //绘画结束
  506. if (!drawing) {
  507. setStageCursor('move');
  508. //设置现在绘画节点的对象为该多边形和顶点的组
  509. // 如果要让顶点和多边形一起拖拽,必须设置,多边形不能被拖拽
  510. poly.setAttr('draggable', false);
  511. currentDrawingShape?.setAttr('draggable', true);
  512. //使所有顶点在顶层显示
  513. stage?.find('Circle').forEach((element) => {
  514. element.moveToTop();
  515. });
  516. pParent.moveToTop();
  517. //添加删除撤销对象
  518. currentDel = currentDrawingShape;
  519. setCurrentGroup(poly.getParent() as Konva.Group);
  520. layer?.draw();
  521. } else {
  522. setStageCursor('crosshair');
  523. poly.getParent()?.setAttr('draggable', false);
  524. }
  525. }
  526. });
  527. pParent?.on('dragend', () => {
  528. if (!isEdit) return;
  529. console.log('dragend');
  530. /** 这里可以把工具的类型用枚举值定义 */
  531. //使所有顶点在顶层显示
  532. stage?.find('Circle').forEach((element) => {
  533. element.moveToTop();
  534. });
  535. //添加删除撤销对象
  536. currentDel = currentDrawingShape;
  537. layer?.draw();
  538. /* vc_setMaskData(); */
  539. // ElMessage({
  540. // message: '修改成功!',
  541. // type: 'success',
  542. // center: true,
  543. // duration: 1000,
  544. // });
  545. setStageCursor('crosshair');
  546. //设置组不能拖动
  547. currentDrawingShape?.setAttr('draggable', false);
  548. });
  549. return poly;
  550. }
  551. /** 根据json数据创建group */
  552. function createGroupByPoints(points: Points) {
  553. var group = new Konva.Group({
  554. name: currentTool.name + 'group',
  555. draggable: false,
  556. });
  557. //添加多边形的点
  558. //绘画多边形
  559. drawPolygon(currentTool, points, group);
  560. for (let i = 0; i < points.length; i += 2) {
  561. const x = points[i];
  562. const y = points[i + 1];
  563. drawCircle(x, y, group, points);
  564. }
  565. // group.setAttrs({ x: groupData.attrs.x, y: groupData.attrs.y })
  566. console.log('group', group);
  567. layer?.add(group);
  568. layer?.draw();
  569. }
  570. /** 画多条线 */
  571. function createLines(lines: Points[]) {
  572. lines.forEach((line) => {
  573. createGroupByPoints(line);
  574. });
  575. }
  576. const removeCurrent = () => {
  577. if (currentDel) {
  578. currentDel.destroy();
  579. currentDel = null;
  580. currentDrawingShape = null;
  581. // ElMessage.success({
  582. // message: '删除成功!',
  583. // center: true,
  584. // duration: 1000,
  585. // });
  586. } else {
  587. ElMessage.warning({ message: '请选择要删除的电子围栏' });
  588. }
  589. layer?.draw();
  590. };
  591. const toObject = () => {
  592. const polyGroups = stage?.find('.polygroup');
  593. const gropuPoints = polyGroups?.map((item) => {
  594. const groupX = item.x();
  595. const groupY = item.y();
  596. const line = (item as Konva.Group).findOne((x: any) => x.className === 'Line') as Konva.Line;
  597. const points = line?.points();
  598. const newPoints: number[][] = [];
  599. /** 存到后端的时候,只给点的坐标信息,不会给group的位置信息,所以要将点的坐标加上group的位移,才是之后点的最终坐标 */
  600. for (let i = 0; i < points.length; i += 2) {
  601. newPoints.push([Math.floor(points[i] + groupX), Math.floor(points[i + 1] + groupY)]);
  602. }
  603. return newPoints;
  604. });
  605. return gropuPoints;
  606. };
  607. const initStageByJSON = (param: { width: number; height: number }) => {
  608. stage?.setAttrs({ width: param.width, height: param.height });
  609. };
  610. const toRawObject = () => {
  611. return stage?.toObject();
  612. };
  613. /** 退出编辑模式 */
  614. const exitEditMode = () => {
  615. setCurrentGroup(null);
  616. isEdit = false;
  617. };
  618. /** 进入编辑模式 */
  619. const setEditMode = () => {
  620. isEdit = true;
  621. };
  622. /** 清空所有元素 */
  623. const clear = () => {
  624. layer?.removeChildren();
  625. };
  626. const setScale = (scale: number) => {
  627. stage?.setAttr('scaleX', scale);
  628. };
  629. defineExpose({
  630. remove: removeCurrent,
  631. toObject,
  632. toRawObject,
  633. createLines,
  634. initStageByJSON,
  635. exitEditMode,
  636. setEditMode,
  637. clear,
  638. setScale,
  639. });
  640. </script>
  641. <style scoped>
  642. #editorMap {
  643. position: absolute;
  644. left: 0;
  645. top: 0;
  646. width: 100%;
  647. height: 100%;
  648. z-index: 8;
  649. }
  650. </style>