找回密码
 立即注册
首页 业界区 业界 根据点信息生成道路以及路口

根据点信息生成道路以及路口

城徉汗 2025-6-2 22:43:56
1.gif
          
2.gif

 
 
一、目标
  1. 生成道路:通过提供的一些随机的点信息,自动扩展成一定宽度的道路,道路具有路沿点、道路中心点分上下行车道,点的方向根据实际车道运行的方向生成。
  2. 生成路口:如果多天道路之间有相交,则可以自动在交叉位置计算出道路路口,方便后续车辆在路口拐弯的计算和展示美观,无线路交叉感。
二、实现原理
  1. 如何生成一条道路
    1) 以每两个点形成一条直线向两侧扩展一定的宽度生成一个面(如图一),但是需要考虑多个连续的线段之间可能会有线段交叉或者无交叉的情况(如图二),
      如果两个线段有交点时需要把舍弃掉部分扩展道路点同时插入交叉点A,如果没有交点则需要插入直线的交点B来将道路连接起来
    
3.png
        
4.png

     2) 将扩展的左、右两侧的道路点信息拼接起来,如果是逆时针,则上下行顺序正确,否则需要将点信息反转
    
5.png

  2. 如何生成相互交叉的道路和路口
    注:同一条道路如果有交叉,不会生成路口
    1)分组道路:如果多条道路在某一个点附近交叉,可以认为这些道路共用一个路口,循环遍历所有道路,如果道路交叉点之间的距离小于某个范围,则认为属于同一个路口
    2) 按组对道路点进行循环,对上下行道路点分别进行交叉点计算,同时生成一个多边形,按照算法获取这个多边形最大的凸包即路口的点信息,
      如图中红色点为多条道路中心线的交叉点,如果红点之间的距离小于一定范围,则认为这三条道路归属一个路口
      每个黑色的线(即上下行边线)相交的点(图中所有黑色的点)组成一个polygon,通过Graham扫描法寻找最大的凸包时会只保留较大的黑色点,三个小黑点由于在凸包范围内则被舍弃
      这样就获取到完整的路口点信息
    
6.png

三、代码逻辑
  1. 简单创建页面
7.gif
8.gif
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4.     <meta charset="UTF-8">
  5.     <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6.     <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7.    
  8.     <title>localhost:8086</title>
  9.    
  10. </head>
  11. <body >
  12.    
  13.         <img  src="https://www.cnblogs.com/./images/road.svg" id="drawRoad">
  14.         <img  src="https://www.cnblogs.com/./images/clear.svg" id="clear">
  15.    
  16.     <canvas id="webgl"></canvas>
  17. </body>
  18. </html>
复制代码
index.html  2. 为了快速测试功能,通过在界面手动戳点来快速创建随机的道路点信息
11.gif
12.gif
  1. // import { pushLine, refresh } from './Line.js';
  2. import * as roadCtrl from '../road/RoadControl.js';
  3. let that = null;
  4. export default class Draw {
  5.     constructor(props) {
  6.         that = this;
  7.         // 鼠标图钉对象
  8.         this.mouseDom = null;
  9.         // 道路拐点信息
  10.         this.points = [];
  11.         this.ctx = document.getElementById(props.id).getContext('2d');
  12.         this.width = document.getElementById(props.id).offsetWidth;
  13.         this.height = document.getElementById(props.id).offsetHeight;
  14.         this.thumbtack = new Image();
  15.         this.thumbtack.src = './images/thumbtack.svg';
  16.         
  17.         this.mouseX = 0;
  18.         this.mouseY = 0;
  19.         this.drawEnd = props.drawEnd;
  20.         this.initMouse();
  21.     }
  22.     initMouse() {
  23.         this.mouseDom = document.createElement('div');
  24.         const imgDom = document.createElement('img');
  25.         imgDom.src = './images/thumbtack-add.svg';
  26.         this.mouseDom.style.position = 'absolute';
  27.         this.mouseDom.style.right = '0px';
  28.         this.mouseDom.style.top = '0px';
  29.         this.mouseDom.style.width = '24px';
  30.         document.body.appendChild(this.mouseDom);
  31.         this.registerEvent();
  32.     }
  33.     registerEvent() {
  34.         this.mouseDom.addEventListener('click', this.clickEvent);
  35.         document.addEventListener('mousemove', this.mousemoveEvent);
  36.         document.addEventListener('keydown', this.keydownEvent);
  37.         document.addEventListener('dblclick', this.dblclickEvent);
  38.     }
  39.     clickEvent(event) {
  40.         that.points.push([event.clientX, event.clientY]);
  41.         that.refresh();
  42.     }
  43.     keydownEvent(event) {
  44.         if (event.key === 'Escape') {
  45.             that.points.pop();
  46.             that.refresh();
  47.         }
  48.     }
  49.     mousemoveEvent(e) {
  50.         that.mouseX = e.clientX;
  51.         that.mouseY = e.clientY;
  52.         that.mouseDom.style.left = e.clientX - 3 + 'px';
  53.         that.mouseDom.style.top = e.clientY - 20 + 'px';
  54.         that.mouseDom.innerHTML = `${e.clientX}, ${e.clientY}`;
  55.         that.refresh();
  56.     }
  57.     dblclickEvent() {
  58.         that.points.pop();
  59.         if (that.drawEnd) {
  60.             that.destory();
  61.             that.drawEnd(that.points);
  62.         }
  63.     }
  64.     refresh() {
  65.         this.ctx.clearRect(0, 0, this.width, this.height);
  66.         this.drawLine(this.mouseX, this.mouseY);
  67.         this.drawPoint();
  68.         roadCtrl.refresh();
  69.     }
  70.     drawLine(lastX, lastY) {
  71.         this.ctx.clearRect(0, 0, this.width, this.height);
  72.         if (this.points.length !==  0) {
  73.             this.ctx.strokeStyle = '#9ec9df';
  74.             this.ctx.lineWidth = 2;
  75.             this.ctx.lineJoin="round";
  76.             this.ctx.beginPath();
  77.             this.ctx.moveTo(...this.points[0]);
  78.             for (let i = 0; i < this.points.length; i++) {
  79.                 this.ctx.lineTo(...this.points[i]);
  80.             }
  81.             this.ctx.lineTo(lastX, lastY);
  82.             this.ctx.stroke();
  83.         }
  84.     }
  85.     drawPoint() {
  86.         for (let i = 0; i < this.points.length; i++) {
  87.             this.ctx.drawImage(this.thumbtack, this.points[i][0] - 11, this.points[i][1] - 20, 24, 24);
  88.         }
  89.     }
  90.     destory() {
  91.         this.ctx.clearRect(0, 0, this.width, this.height);
  92.         this.mouseDom.removeEventListener('click', this.clickEvent);
  93.         document.removeEventListener('mousemove', this.mousemoveEvent);
  94.         document.removeEventListener('keydown', this.keydownEvent);
  95.         document.removeEventListener('dblclick', this.dblclickEvent);
  96.         this.mouseDom.remove();
  97.     }
  98. }
复制代码
Draw.js  3. 创建工具文件,计算是否顺时针、计算凸包等算法功能
13.gif
14.gif
  1. /**
  2. * 根据贝塞尔公式获取一条平滑的曲线
  3. * @param {*} points
  4. * @param {*} numSegments
  5. * @returns
  6. */
  7. function getBezierPoints(points, numSegments = 8) {
  8.     const bezierPoints = [];
  9.     for (let i = 0; i < points.length - 1; i++) {
  10.         const p0 = points[i];
  11.         const p1 = points[i + 1];
  12.         // 计算控制点
  13.         const cp1 = {
  14.             x: p0[0] + (p1[0] - p0[0]) / 3,
  15.             y: p0[1] + (p1[1] - p0[1]) / 3
  16.         };
  17.         const cp2 = {
  18.             x: p0[0] + 2 * (p1[0] - p0[0]) / 3,
  19.             y: p0[1] + 2 * (p1[1] - p0[1]) / 3
  20.         };
  21.         // 计算贝塞尔曲线上的点
  22.         for (let t = 0; t <= 1; t += 1 / numSegments) {
  23.             const t2 = t * t;
  24.             const t3 = t2 * t;
  25.             const mt = 1 - t;
  26.             const mt2 = mt * mt;
  27.             const mt3 = mt2 * mt;
  28.             const x = mt3 * p0[0] + 3 * mt2 * t * cp1.x + 3 * mt * t2 * cp2.x + t3 * p1[0];
  29.             const y = mt3 * p0[1] + 3 * mt2 * t * cp1.y + 3 * mt * t2 * cp2.y + t3 * p1[1];
  30.             if (bezierPoints.length === 0 || x !== bezierPoints[bezierPoints.length - 1][0] && y !== bezierPoints[bezierPoints.length - 1][1]) {
  31.                 bezierPoints.push([x, y]);
  32.             }
  33.         }
  34.     }
  35.     return bezierPoints;
  36. }
  37. /**
  38. * 求两个线段的交点
  39. * @param {*} line1
  40. * @param {*} line2
  41. * @returns
  42. */
  43. function getIntersectionPoint(line1, line2) {
  44.     const [p11, p12] = [...line1];
  45.     const [p21, p22]  = [...line2];
  46.     // 计算线段1的向量
  47.     const dx1 = p12[0] - p11[0];
  48.     const dy1 = p12[1] - p11[1];
  49.     // 计算线段2的向量
  50.     const dx2 = p22[0] - p21[0];
  51.     const dy2 = p22[1] - p21[1];
  52.     // 计算行列式
  53.     const determinant = dx1 * dy2 - dy1 * dx2;
  54.     // 如果行列式为0,则两条线段平行或共线,没有交点
  55.     if (determinant === 0) {
  56.         return [];
  57.     }
  58.     // 计算参数t1和t2
  59.     const t1 = ((p21[0] - p11[0]) * dy2 - (p21[1] - p11[1]) * dx2) / determinant;
  60.     const t2 = ((p21[0] - p11[0]) * dy1 - (p21[1] - p11[1]) * dx1) / determinant;
  61.     // 检查交点是否在线段范围内
  62.     if (t1 >= 0 && t1 <= 1 && t2 >= 0 && t2 <= 1) {
  63.         // 计算交点坐标
  64.         const x = p11[0] + t1 * dx1;
  65.         const y = p11[1] + t1 * dy1;
  66.         return [parseInt(x), parseInt(y)];
  67.     }
  68.     // 没有交点
  69.     return [];
  70. }
  71. /**
  72. * 求两条直线的交点
  73. * @returns
  74. */
  75. function getIntersection(line1, line2) {
  76.     // 计算直线1的方程
  77.     const [x1, y1] = line1[0];
  78.     const [x2, y2] = line1[1];
  79.     const isVertical1 = x1 === x2;
  80.     let A1, B1, C1;
  81.     if (isVertical1) {
  82.         A1 = 1;
  83.         B1 = 0;
  84.         C1 = -x1;
  85.     } else {
  86.         const m1 = (y2 - y1) / (x2 - x1);
  87.         const b1 = y1 - m1 * x1;
  88.         A1 = m1;
  89.         B1 = -1;
  90.         C1 = b1;
  91.     }
  92.     // 计算直线2的方程
  93.     const [x3, y3] = line2[0];
  94.     const [x4, y4] = line2[1];
  95.     const isVertical2 = x3 === x4;
  96.     let A2, B2, C2;
  97.     if (isVertical2) {
  98.         A2 = 1;
  99.         B2 = 0;
  100.         C2 = -x3;
  101.     } else {
  102.         const m2 = (y4 - y3) / (x4 - x3);
  103.         const b2 = y3 - m2 * x3;
  104.         A2 = m2;
  105.         B2 = -1;
  106.         C2 = b2;
  107.     }
  108.     // 判断是否平行于 Y 轴
  109.     if (isVertical1 && isVertical2) {
  110.         // 两条直线都平行于 Y 轴
  111.         if (x1 === x3) {
  112.             // 两条直线重合
  113.             return null; // 有无数个交点
  114.         } else {
  115.             // 两条直线平行但不重合
  116.             return null; // 没有交点
  117.         }
  118.     } else if (isVertical1) {
  119.         // 第一条直线平行于 Y 轴
  120.         const x = x1;
  121.         const y = (-A2 * x - C2) / B2;
  122.         return [x, y];
  123.     } else if (isVertical2) {
  124.         // 第二条直线平行于 Y 轴
  125.         const x = x3;
  126.         const y = (-A1 * x - C1) / B1;
  127.         return [x, y];
  128.     } else {
  129.         // 两条直线都不平行于 Y 轴
  130.         const det = A1 * B2 - A2 * B1;
  131.         if (det === 0) {
  132.             // 两条直线平行或重合
  133.             return null; // 没有唯一交点
  134.         } else {
  135.             // 计算交点坐标
  136.             const x = (B1 * C2 - B2 * C1) / det;
  137.             const y = (A2 * C1 - A1 * C2) / det;
  138.             return [x, y];
  139.         }
  140.     }
  141. }
  142. /**
  143. * 计算三个点的重心位置
  144. */
  145. function calTriangleCenter(p1, p2, p3) {
  146.     const [x1, y1] = p1;
  147.     const [x2, y2] = p2;
  148.     const [x3, y3] = p3;
  149.     const centerX = (x1 + x2 + x3) / 3;
  150.     const centerY = (y1 + y2 + y3) / 3;
  151.     return [centerX, centerY];
  152. }
  153. /**
  154. * 判断一个多边形是否是顺时针,如果返回true则为顺时针,false为逆时针,
  155. * 需要考虑坐标系和普通坐标系相反的问题
  156. * @param {*} poly
  157. * @returns
  158. */
  159. function isClockWise(poly) {
  160.     if(!poly || poly.length < 3) return null;
  161.     let end = poly.length - 1;
  162.     let sum = poly[end][0] * poly[0][1] - poly[0][0] * poly[end][1];
  163.     for(let i = 0; i < end; ++i) {
  164.         const n = i + 1;
  165.         sum += poly[i][0] * poly[n][1] - poly[n][0] * poly[i][1];
  166.     }
  167.     return sum > 0;
  168. }
  169. /**
  170. * 根据给定的多个点,采用Graham扫描法寻找最大的凸包
  171. */
  172. function getMaxPolygon(points) {
  173.     // 计算两个点之间的距离
  174.     function distance(p1, p2) {
  175.         return Math.sqrt((p1[0] - p2[0]) ** 2 + (p1[1] - p2[1]) ** 2);
  176.     }
  177.     // 计算叉积
  178.     function cross(o, a, b) {
  179.         return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0]);
  180.     }
  181.     // 极角排序比较函数
  182.     function angleCompare(base) {
  183.         return function(p1, p2) {
  184.             const angle1 = Math.atan2(p1[1] - base[1], p1[0] - base[0]);
  185.             const angle2 = Math.atan2(p2[1] - base[1], p2[0] - base[0]);
  186.             if (angle1 === angle2) {
  187.                 return distance(base, p1) - distance(base, p2);
  188.             }
  189.             return angle1 - angle2;
  190.         };
  191.     }
  192.     if (points.length < 3) return points;
  193.     // 选择基准点
  194.     const base = points.reduce((min, p) => p[1] < min[1] || (p[1] === min[1] && p[0] < min[0]) ? p : min, points[0]);
  195.     // 极角排序
  196.     points.sort(angleCompare(base));
  197.     // 构建凸包
  198.     const stack = [points[0], points[1], points[2]];
  199.     for (let i = 3; i < points.length; i++) {
  200.         while (stack.length > 1 && cross(stack[stack.length - 2], stack[stack.length - 1], points[i]) <= 0) {
  201.             stack.pop();
  202.         }
  203.         stack.push(points[i]);
  204.     }
  205.     return stack;
  206. }
  207. /**
  208. * 拷贝数据
  209. */
  210. function clone(data) {
  211.     return JSON.parse(JSON.stringify(data));
  212. }
  213. function createRandomId(prefix) {
  214.     return prefix + '_' + 'xx-xxxx-4xxx-yxxx'.replace(/[xy]/g, (c) => {
  215.         var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
  216.         return v.toString(16);
  217.     });
  218. }
  219. /**
  220. * 计算距离
  221. */
  222. function distance(point1, point2) {
  223.     return Math.sqrt(Math.pow(point1[0] - point2[0], 2) + Math.pow(point1[1] - point2[1], 2), 2);
  224. }
  225. export {
  226.     createRandomId,
  227.     getBezierPoints,
  228.     getIntersectionPoint,
  229.     isClockWise,
  230.     getIntersection,
  231.     calTriangleCenter,
  232.     clone,
  233.     getMaxPolygon,
  234.     distance
  235. }
复制代码
Util.js  4. 创建主文件,与UI交互,获取道路、路口数据,绘制道路、路口功能
15.gif
16.gif
  1. import { refresh } from './control/Line.js';
  2. import Draw from './control/Draw.js';
  3. import * as roadCtrl from './road/RoadControl.js';
  4. import * as crossCtrl from './road/CrossControl.js';
  5. import { distance, getIntersectionPoint, getMaxPolygon } from './road/Util.js';
  6. let flag = false;
  7. let drawIns = null;
  8. let canvasDom = null;
  9. let ctx = null;
  10. function initEvent() {
  11.     const map = {
  12.         drawRoad,
  13.         clear
  14.     }
  15.     const list = document.getElementsByClassName('button-item');
  16.     for (let i = 0; i < list.length; i++) {
  17.         list[i].addEventListener('click', (e) => {
  18.             map[e.target.id]();
  19.         })
  20.     }
  21.     canvasDom = document.getElementById('webgl');
  22.     ctx = canvasDom.getContext('2d');
  23.     canvasDom.setAttribute('width', canvasDom.offsetWidth);
  24.     canvasDom.setAttribute('height', canvasDom.offsetHeight);
  25.     roadCtrl.setCtx(ctx);
  26.     crossCtrl.setCtx(ctx);
  27. }
  28. function drawRoad() {
  29.     if (!flag) {
  30.         flag = true;
  31.         drawIns = new Draw({ id: 'webgl', drawEnd: (coords) => {
  32.             roadCtrl.addRoad({ coords, width: 20 });
  33.             roadCtrl.refresh();
  34.             flag = false;
  35.             const allRoads = roadCtrl.getAllRoad();
  36.             getCross(allRoads);
  37.             console.log(crossCtrl.getAllCross());
  38.         } });
  39.     } else {
  40.         drawIns.destory();
  41.         flag = false;
  42.         refresh();
  43.     }
  44. }
  45. /**
  46. * 获取所有的焦点
  47. */
  48. function getInterPoint(line1, line2) {
  49.     const inter = [];
  50.     for(let i = 0; i < line1.length - 1; i++){
  51.         for(let j = 0; j < line2.length - 1; j++){
  52.             const interPoint =  getIntersectionPoint([line1[i], line1[i + 1]], [line2[j], line2[j + 1]]);
  53.             if (interPoint.length !== 0) {
  54.                 inter.push(interPoint);
  55.             }
  56.         }
  57.     }
  58.     return inter;
  59. }
  60. /**
  61. * 判断两个点之间相近
  62. * @param {*} point1 点1
  63. * @param {*} point2 点2
  64. * @param {*} tolerance 容忍值
  65. * @returns
  66. */
  67. function isNear(point1, point2, tolerance) {
  68.     return distance(point1, point2) < tolerance;
  69. }
  70. /**
  71. * 判断是否存在道路列表中
  72. */
  73. function isNotExist(roads, id) {
  74.     return roads.filter(e => e.id === id).length === 0;
  75. }
  76. /**
  77. * 从多个点中获取距离基准点最近的点
  78. * @param {*} points
  79. * @param {*} basePoint
  80. * @param {*} tolerance
  81. */
  82. function getNearestPoint(points, basePoint, tolerance = 160) {
  83.     const pointDis = points.map(e => {
  84.         return {
  85.             point: e,
  86.             dis: distance(e, basePoint)
  87.         };
  88.     });
  89.     pointDis.sort((a, b) => a.dis - b.dis);
  90.     if (distance(pointDis[0].point, basePoint) < tolerance) {
  91.         return pointDis[0].point;
  92.     } else {
  93.         return [];
  94.     }
  95. }
  96. function groupCross(roads) {
  97.     // 计算原则,多条路相交于一点或者近乎一点时
  98.     // same 格式 XY 轴坐标联合作为key值存储数据
  99.     // {
  100.     //     'x,y': {
  101.     //         point: [], 道路交点,多条道路只存储一个交点
  102.     //         links: [] 该路口的关联道路信息
  103.     //     }
  104.     // }
  105.     const same = {};
  106.     for (let i = 0; i < roads.length - 1; i++) {
  107.         for (let j = i + 1; j < roads.length; j++) {
  108.             const tempInter = getInterPoint(roads[i].CCoords, roads[j].CCoords);
  109.             tempInter.forEach(e => {
  110.                 let flag = false;
  111.                 for (const o in same) {
  112.                     if (isNear(same[o].point, e, 40)) {
  113.                         if (isNotExist(same[o].links, roads[i].id)) {
  114.                             same[o].links.push(roads[i]);
  115.                         }
  116.                         if (isNotExist(same[o].links, roads[j].id)) {
  117.                             same[o].links.push(roads[j]);
  118.                         }
  119.                         flag = true;
  120.                     }
  121.                 }
  122.                 if (!flag) {
  123.                     same[e.join(',')] = {
  124.                         point: e,
  125.                         links: [roads[i], roads[j]]
  126.                     };
  127.                 }
  128.             });
  129.         }
  130.     }
  131.     const linkVals = Object.values(same);
  132.     const allInter = [];
  133.     for (let i = 0; i < linkVals.length; i++) {
  134.         allInter[i] = {
  135.             coords: [],
  136.             links: linkVals[i].links
  137.         };
  138.         for (let j = 0; j < linkVals[i].links.length - 1; j++) {
  139.             for (let m = j + 1; m < linkVals[i].links.length; m++) {
  140.                 const cPoint = linkVals[i].point;
  141.                 const LL = getInterPoint(linkVals[i].links[j].LCoords, linkVals[i].links[m].LCoords, cPoint);
  142.                 const LR = getInterPoint(linkVals[i].links[j].LCoords, linkVals[i].links[m].RCoords, cPoint);
  143.                 const RL = getInterPoint(linkVals[i].links[j].RCoords, linkVals[i].links[m].LCoords, cPoint);
  144.                 const RR = getInterPoint(linkVals[i].links[j].RCoords, linkVals[i].links[m].RCoords, cPoint);
  145.                 if (LL.length !== 0) {
  146.                     const temp = getNearestPoint(LL, cPoint);
  147.                     if (temp.length !== 0) {
  148.                         allInter[i].coords.push(temp);
  149.                     }
  150.                 }
  151.                 if (LR.length !== 0) {
  152.                     const temp = getNearestPoint(LR, cPoint);
  153.                     if (temp.length !== 0) {
  154.                         allInter[i].coords.push(temp);
  155.                     }
  156.                 }
  157.                 if (RL.length !== 0) {
  158.                     const temp = getNearestPoint(RL, cPoint);
  159.                     if (temp.length !== 0) {
  160.                         allInter[i].coords.push(temp);
  161.                     }
  162.                 }
  163.                 if (RR.length !== 0) {
  164.                     const temp = getNearestPoint(RR, cPoint);
  165.                     if (temp.length !== 0) {
  166.                         allInter[i].coords.push(temp);
  167.                     }
  168.                 }
  169.             }
  170.         }
  171.     }
  172.     return allInter.filter(e => e.length !== 0);
  173. }
  174. /**
  175. * 计算道路口
  176. */
  177. function getCross(roads) {
  178.     crossCtrl.removeAll();
  179.     const allInter = groupCross(roads);
  180.     allInter.forEach(e => {
  181.         const crossObj = getMaxPolygon(e.coords);
  182.         crossCtrl.add({
  183.             coords: crossObj,
  184.             linkRoad: e.links
  185.         });
  186.         // drawPolygon(out);
  187.     });
  188. }
  189. function drawPoint(points, color = 'red') {
  190.     ctx.save()
  191.     points.forEach(e => {
  192.         ctx.beginPath();
  193.         ctx.arc(...e, 3, 0, 2 * Math.PI);
  194.         ctx.fillStyle = color; // 设置原点的颜色
  195.         ctx.fill();
  196.         ctx.closePath();   
  197.     });
  198.     ctx.restore();
  199. }
  200. function drawPolygon(points) {
  201.     if (points.length === 0) {
  202.         return;
  203.     }
  204.     ctx.save();
  205.     ctx.beginPath();
  206.     ctx.strokeStyle = '#dbdae3';
  207.     ctx.lineWidth = 5;
  208.     ctx.moveTo(...points[0]);
  209.     points.forEach(e => {
  210.         ctx.lineTo(...e);
  211.     });
  212.     ctx.closePath();
  213.     ctx.stroke();
  214.     ctx.fillStyle = '#dbdae3';
  215.     ctx.fill();
  216.     ctx.restore();
  217. }
  218. function clear() {
  219.     roadCtrl.removeAll();
  220.     ctx.clearRect(0, 0, canvasDom.offsetWidth, canvasDom.offsetHeight);
  221. }
  222. function drawId(text, points) {
  223.     ctx.save();
  224.     ctx.font = '15px Arial';
  225.     ctx.fillStyle = 'blue'; // 文字颜色为蓝色
  226.     ctx.textAlign = 'center'; // 水平对齐方式为居中
  227.     ctx.textBaseline = 'middle'; // 垂直对齐方式为居中
  228.     ctx.fillText(text, ...points); // 在坐标(100, 100)处绘制文字
  229.     ctx.restore();
  230. }
  231. window.onload = () => {
  232.     initEvent();
  233. }
复制代码
main.js  5. 创建道路类,包括绘制道路、获取扩展点等
17.gif
18.gif
  1. import { getBezierPoints, getIntersectionPoint, isClockWise, getIntersection, clone, calTriangleCenter } from './Util.js';
  2. class Road {
  3.     constructor(props) {
  4.         // 车道ID
  5.         this.id = props.id;
  6.         // 顶点数
  7.         this.turnCoords = props.coords;
  8.         // 单向车道数
  9.         this.laneNum = 1;
  10.         // 道路宽度
  11.         this.width = props.width || 20;
  12.         // 车道中心点信息
  13.         this.CCoords = [];
  14.         // 左车道点信息
  15.         this.LCoords = [];
  16.         // 右车道点信息
  17.         this.RCoords = [];
  18.         this.ctx = props.ctx;
  19.         this.init();
  20.     }
  21.     init() {
  22.         this.extendRoadCoord();
  23.         this.draw();
  24.     }
  25.     /**
  26.      * 获取线段上垂直的点
  27.      * @param {*} line
  28.      * @param {*} point
  29.      */
  30.     getVerticalPoint(line, point, width) {
  31.         const [x1, y1] = [...line[0]];
  32.         const [x2, y2] = [...line[1]];
  33.         const [px, py] = [...point];
  34.         
  35.         if (y1 - y2 !== 0) {
  36.             const beta = Math.abs(Math.cos(Math.atan((x2 - x1) / (y1 - y2))) * width);
  37.             const tempX1 = px + beta;
  38.             const tempX2 = px - beta;
  39.             const tempY1 = (x2 - x1) / (y1 - y2) * tempX1
  40.                 + (py * (y1 - y2) - px * (x2 - x1)) / (y1 - y2);
  41.             const tempY2 = (x2 - x1) / (y1 - y2) * tempX2
  42.                 + (py * (y1 - y2) - px * (x2 - x1)) / (y1 - y2);
  43.             
  44.             return [[tempX1, tempY1], [tempX2, tempY2]];
  45.         } else {
  46.             return [[px, py - width], [px, py + width]];
  47.         }
  48.     }
  49.     /**
  50.      * 获取道路扩展后的顶点信息
  51.      * 原理:通过判断两条线段是否有交点,如果有交点则代表扩展的点需要舍弃一个同时插入交点,否则线路就会有交叉
  52.      *       如果没有交点,则代表线段不相交,需要插入两条线段代表的直线的交点
  53.      */
  54.     getSideCoord() {
  55.         const [left, right] = [[], []];
  56.         for(let i = 0; i < this.turnCoords.length - 1; i++){
  57.             const polygon = [];
  58.             
  59.             const preSides = this.getVerticalPoint([this.turnCoords[i], this.turnCoords[i + 1]], this.turnCoords[i], this.width);
  60.             const nextSides = this.getVerticalPoint([this.turnCoords[i], this.turnCoords[i + 1]], this.turnCoords[i + 1], this.width);
  61.             
  62.             polygon.push(preSides[0], nextSides[0], nextSides[1], preSides[1]);
  63.             
  64.             if (isClockWise(polygon)) {
  65.                 left.push(preSides[0], nextSides[0]);
  66.                 right.push(preSides[1], nextSides[1]);
  67.             } else {
  68.                 left.push(preSides[1], nextSides[1]);
  69.                 right.push(preSides[0], nextSides[0]);
  70.             }
  71.         }
  72.         return { left, right };
  73.     }
  74.     /**
  75.      * 根据获取的边线顶点
  76.      */
  77.     extendRoadCoord() {
  78.         const sides = this.getSideCoord();
  79.         if (this.turnCoords.length <= 2) {
  80.             const cloneLeft = sides.left;
  81.             const cloneRight = sides.right;
  82.             const polygon = cloneLeft.concat(cloneRight.reverse());
  83.             if (isClockWise(polygon)) {
  84.                 this.LCoords = sides.left;
  85.                 this.RCoords = sides.right;
  86.             } else {
  87.                 this.LCoords = sides.left;
  88.                 this.RCoords = sides.right.reverse();
  89.             }
  90.             this.CCoords = this.turnCoords;
  91.             this.LCoords.push(this.LCoords[this.LCoords.length - 1]);
  92.             this.LCoords.unshift(this.LCoords[0]);
  93.             this.RCoords.push(this.RCoords[this.RCoords.length - 1]);
  94.             this.RCoords.unshift(this.RCoords[0]);
  95.         } else {
  96.             const left = sides.left;
  97.             const right = sides.right;
  98.             let [tempLeft, tempRight] = [[], []]; // 最终生成的道路左右边线顶点
  99.             let [preLeftInterPoint, preRightInterPoint] = [];
  100.             for (let i = 0; i < left.length - 2; i += 2) {
  101.                 const interPoint = getIntersectionPoint([left[i], left[i + 1]], [left[i + 2], left[i + 3]]);
  102.                 if (interPoint.length !== 0) {
  103.                     if (i === 0) {
  104.                         tempLeft.push(left[i], interPoint);
  105.                     } else {
  106.                         tempLeft.push(interPoint);
  107.                     }
  108.                     preLeftInterPoint = interPoint;
  109.                 } else {
  110.                     // 线所组成的直线对应的交点
  111.                     const straightInterPoint = getIntersection([left[i], left[i + 1]], [left[i + 2], left[i + 3]]);
  112.                     if (!preLeftInterPoint) {
  113.                         if (i === 0) {
  114.                             tempLeft.push(left[i], straightInterPoint);
  115.                         } else {
  116.                             tempLeft.push(straightInterPoint);
  117.                         }
  118.                     } else {
  119.                         tempLeft.push(straightInterPoint);
  120.                     }
  121.                     preLeftInterPoint = null;
  122.                 }
  123.                 if (i === left.length - 4) {
  124.                     tempLeft.push(left[left.length - 1]);
  125.                 }
  126.             }
  127.             for (let i = 0; i < right.length - 2; i += 2) {
  128.                 const interPoint = getIntersectionPoint([right[i], right[i + 1]], [right[i + 2], right[i + 3]]);
  129.                 if (interPoint.length !== 0) {
  130.                     if (i === 0) {
  131.                         tempRight.push(right[i], interPoint);
  132.                     } else {
  133.                         tempRight.push(interPoint);
  134.                     }
  135.                     preRightInterPoint = interPoint;
  136.                 } else {
  137.                     // 线所组成的直线对应的交点
  138.                     const straightInterPoint = getIntersection([right[i], right[i + 1]], [right[i + 2], right[i + 3]]);
  139.                     if (!preRightInterPoint) {
  140.                         if (i === 0) {
  141.                             tempRight.push(right[i], straightInterPoint);
  142.                         } else {
  143.                             tempRight.push(straightInterPoint);
  144.                         }
  145.                     } else {
  146.                         tempRight.push(straightInterPoint);
  147.                     }
  148.                     preRightInterPoint = null;
  149.                 }
  150.                 if (i === right.length - 4) {
  151.                     tempRight.push(right[right.length - 1]);
  152.                 }
  153.             }
  154.             this.drawPoint([tempLeft[tempLeft.length - 1], tempLeft[0]], 'red');
  155.             this.drawPoint([tempRight[tempRight.length - 1], tempRight[0]], 'blue');
  156.             // 为了在末端绘制的更加圆滑,所以增加几个重复点,使用贝塞尔曲线绘制底色时不会出现圆弧
  157.             tempLeft.push(tempLeft[tempLeft.length - 1]);
  158.             tempLeft.unshift(tempLeft[0]);
  159.             tempRight.push(tempRight[tempRight.length - 1]);
  160.             tempRight.unshift(tempRight[0]);
  161.             tempRight.reverse();
  162.             this.LCoords = getBezierPoints(tempLeft);
  163.             this.RCoords = getBezierPoints(tempRight);
  164.             this.CCoords = getBezierPoints(this.turnCoords);
  165.             
  166.         }
  167.     }
  168.     /**
  169.      * 绘制车道外轮廓
  170.      */
  171.     drawOutline() {
  172.         // 绘制左侧车道
  173.         this.drawLine(this.LCoords);
  174.         // 绘制右侧车道
  175.         this.drawLine(this.RCoords);
  176.         // 绘制车道中心线
  177.         this.drawLine(this.CCoords, { color: '#aaa', dash: false, width: 2 });
  178.     }
  179.     /**
  180.      * 绘制道路背景色
  181.      */
  182.     drawBackground() {
  183.         const cloneLeft = clone(this.LCoords);
  184.         const cloneRight = clone(this.RCoords);
  185.         const polygon = cloneLeft.concat(cloneRight);
  186.         this.ctx.save();
  187.         this.ctx.beginPath();
  188.         this.ctx.moveTo(...polygon[0]);
  189.         for (let i = 0; i < polygon.length - 1; i++) {
  190.             const xc = (polygon[i][0] + polygon[i + 1][0]) / 2;
  191.             const yc = (polygon[i][1] + polygon[i + 1][1]) / 2;
  192.             this.ctx.quadraticCurveTo(...polygon[i], xc, yc);
  193.         }
  194.         this.ctx.lineTo(...polygon[polygon.length - 1]);
  195.         this.ctx.lineTo(...polygon[polygon.length - 1]);
  196.         this.ctx.closePath();
  197.         this.ctx.fillStyle = '#dbdae3';
  198.         this.ctx.fill();
  199.         this.ctx.restore();
  200.     }
  201.     draw() {
  202.         this.drawBackground();
  203.         this.drawOutline();
  204.         this.drawLane();
  205.     }
  206.     /**
  207.      * 绘制车道线
  208.      */
  209.     drawLane() {
  210.     }
  211.     drawLine(points, style = {}) {
  212.         this.ctx.save();
  213.         this.ctx.strokeStyle = style.color || '#666';
  214.         this.ctx.lineWidth = style.width || 3;
  215.         this.ctx.lineJoin = 'round';
  216.         if (style.dash) {
  217.             this.ctx.setLineDash([this.width * 0.8, this.width * 0.6]);
  218.         }
  219.         this.ctx.beginPath();
  220.         this.ctx.moveTo(...points[0]);
  221.         for (let i = 0; i < points.length - 1; i++) {
  222.             const xc = (points[i][0] + points[i + 1][0]) / 2;
  223.             const yc = (points[i][1] + points[i + 1][1]) / 2;
  224.             this.ctx.quadraticCurveTo(...points[i], xc, yc);
  225.         }
  226.         this.ctx.lineTo(...points[points.length - 1]);
  227.         this.ctx.stroke();
  228.         this.ctx.restore();
  229.         // 主要用来测试,直观的观察点的位置以及线的方向顺序
  230.         this.drawArrow(points);
  231.         // this.drawPoint(points, style.color);
  232.     }
  233.     /**
  234.      * 计算方向向量  用于测试
  235.      * @param {*} start
  236.      * @param {*} end
  237.      * @returns
  238.      */
  239.     calculateDirectionVector(start, end) {
  240.         return {
  241.             dx: end.x - start.x,
  242.             dy: end.y - start.y
  243.         };
  244.     }
  245.     /**
  246.      * 计算中间点 用于测试
  247.      * @param {*} start
  248.      * @param {*} end
  249.      * @returns
  250.      */
  251.     calculateMiddlePoint(start, end) {
  252.         return {
  253.             x: (start.x + end.x) / 2,
  254.             y: (start.y + end.y) / 2
  255.         };
  256.     }
  257.     /**
  258.      * 绘制方向向量  用于测试
  259.      * @param {*} middle
  260.      * @param {*} direction
  261.      */
  262.     drawDirectionVector(middle, direction) {
  263.         const arrowLength = 10;
  264.         const angle = Math.atan2(direction.dy, direction.dx);
  265.         // 计算箭头的两个端点
  266.         const arrowX1 = middle.x + arrowLength * Math.cos(angle - Math.PI / 6);
  267.         const arrowY1 = middle.y + arrowLength * Math.sin(angle - Math.PI / 6);
  268.         const arrowX2 = middle.x + arrowLength * Math.cos(angle + Math.PI / 6);
  269.         const arrowY2 = middle.y + arrowLength * Math.sin(angle + Math.PI / 6);
  270.         // 绘制箭头
  271.         this.ctx.save();
  272.         this.ctx.strokeStyle = '#666';
  273.         this.ctx.beginPath();
  274.         this.ctx.moveTo(middle.x, middle.y);
  275.         this.ctx.lineTo(arrowX1, arrowY1);
  276.         this.ctx.moveTo(middle.x, middle.y);
  277.         this.ctx.lineTo(arrowX2, arrowY2);
  278.         this.ctx.stroke();
  279.         this.ctx.restore();
  280.     }
  281.     /**
  282.      * 绘制箭头,主要用于测试,查看绘制线路的方向
  283.      */
  284.     drawArrow(points) {
  285.         for (let i = 0; i < points.length - 1; i++) {
  286.             const start = { x: points[i][0], y: points[i][1] };
  287.             const end = { x: points[i + 1][0], y: points[i + 1][1] };
  288.             const directionVector = this.calculateDirectionVector(start, end);
  289.             const middlePoint = this.calculateMiddlePoint(start, end);
  290.             this.drawDirectionVector(middlePoint, directionVector);
  291.         }
  292.     }
  293.     drawPoint(points, color) {
  294.         this.ctx.save()
  295.         points.forEach(e => {
  296.             this.ctx.beginPath();
  297.             this.ctx.arc(...e, 3, 0, 2 * Math.PI);
  298.             this.ctx.fillStyle = color; // 设置原点的颜色
  299.             this.ctx.fill();
  300.             this.ctx.closePath();   
  301.         });
  302.         this.ctx.restore();
  303.     }
  304. }
  305. export default Road;
复制代码
Road.js  6. 创建道路管理器,用于存储、新建、删除和刷新道路
19.gif
20.gif
  1. import Road from './Road.js';
  2. import { createRandomId } from './Util.js';
  3. let instances = []; // 道路实例
  4. let ctx = null; // canvas上下文
  5. function setCtx(context) {
  6.     ctx = context;
  7. }
  8. /**
  9. * 添加道路
  10. */
  11. function addRoad(param) {
  12.     instances.push(new Road({
  13.         id: param.id || createRandomId('road'),
  14.         coords: param.coords,
  15.         width: param.width,
  16.         ctx
  17.     }));
  18. }
  19. /**
  20. * 删除道路
  21. */
  22. function removeRoad(id) {
  23.     const index = instances.findIndex(e => e.id === id);
  24.     instances.splice(index, 1);
  25. }
  26. /**
  27. * 刷新绘制道路
  28. */
  29. function refresh() {
  30.     instances.forEach(e => {
  31.         e.draw();
  32.     });
  33. }
  34. function removeAll() {
  35.     instances = [];
  36. }
  37. function getAllRoad() {
  38.     return instances;
  39. }
  40. export {
  41.     setCtx,
  42.     addRoad,
  43.     removeRoad,
  44.     refresh,
  45.     removeAll,
  46.     getAllRoad
  47. }
复制代码
RoadControl.js  7. 创建路口类
21.gif
22.gif
  1. class Cross {
  2.     constructor(props) {
  3.         // 路口ID
  4.         this.id = props.id;
  5.         // 路口坐标
  6.         this.coords = props.coords;
  7.         // 路口连接的道路
  8.         this.linkRoad = props.linkRoad;
  9.         
  10.         this.ctx = props.ctx;
  11.         this.draw();
  12.     }
  13.     draw() {
  14.         if (this.coords.length === 0) {
  15.             return;
  16.         }
  17.         this.ctx.save();
  18.         this.ctx.beginPath();
  19.         this.ctx.strokeStyle = '#dbdae3';
  20.         this.ctx.lineWidth = 5;
  21.         this.ctx.moveTo(...this.coords[0]);
  22.         this.coords.forEach(e => {
  23.             this.ctx.lineTo(...e);
  24.         });
  25.         this.ctx.closePath();
  26.         this.ctx.stroke();
  27.         this.ctx.fillStyle = '#dbdae3';
  28.         this.ctx.fill();
  29.         this.ctx.restore();
  30.     }
  31. }
  32. export default Cross;
复制代码
Cross.js  8. 创建路口管理器,用于存储、新建、删除等功能
23.gif
24.gif
  1. import Cross from './Cross.js';
  2. import { createRandomId } from './Util.js';
  3. const instances = [];
  4. let ctx = null;
  5. function setCtx(context) {
  6.     ctx = context;
  7. }
  8. function add(param) {
  9.     instances.push(new Cross({
  10.         id: param.id || createRandomId('cross'),
  11.         coords: param.coords,
  12.         linkRoad: param.linkRoad,
  13.         ctx
  14.     }));
  15. }
  16. function remove() {
  17. }
  18. function removeAll() {
  19.     instances.splice(0, instances.length);
  20. }
  21. function getAllCross() {
  22.     return instances;
  23. }
  24. function refresh() {
  25.     instances.forEach(e => {
  26.         e.draw();
  27.     })
  28. }
  29. export { setCtx, add, remove, removeAll, getAllCross, refresh };
复制代码
CrossControl.js 

来源:程序园用户自行投稿发布,如果侵权,请联系站长删除
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
9.jpg
10.jpg

相关推荐

您需要登录后才可以回帖 登录 | 立即注册