canvas给不规则图形添加点击事件
有这么一个需求,把传过来的四个坐标,连成一个图形(可能是规则的,也可能是不规则的),点击某个图形,显示当前这个图形的信息
//数据格式dataList: {lonLatList: nullseatId: 1//图形idstate: 0//状态vehicleNo: null//车牌号xyList: [//根据经纬度转换的xy坐标[58, 511],[81, 503],[23, 462],[0, 470],[58, 511]]}
因为canvas的y坐标是向下的,所以拿到数据后先翻转y坐标
polygons = polygonsInversionY(dataList.map(item => {const list = item.xyListconst len = list.length// 如果首尾是同一个结点,则去掉尾结点if (list.length > 1) {const lastIndex = list.length - 1if (list[0][0] === list[lastIndex][0] && list[0][1] === list[lastIndex][1]) {return list.filter((_, index) => index < lastIndex)}}return list}))drawPolygons = polygons
翻转后的坐标
根据翻转之后的坐标开始绘图
效果图
图形绘制完毕,添加点击功能,点哪个显示哪个的信息
Mycanvas.addEventListener('click', handClick)function handClick(e) {const canvasInfo = Mycanvas.getBoundingClientRect() //获取canvas到浏览器可视范围的距离rectangles = getRectangles(drawPolygons)//拿到每组坐标最大范围的坐标 [0, 0, 81, 49]...const index = inPolygons([e.clientX - canvasInfo.left, e.clientY - canvasInfo.top], drawPolygons, rectangles)//获取点击图形的索引(如何获取参考下图)tipsTop = Number(sessionStorage.getItem('top'))+canvasInfo.top-67tipsLeft = sessionStorage.getItem('left')//根据点击索引,显示当前图形的信息if(index>=0) {let content = ''let seatId = dataList[index].seatIdlet vehicleNo = dataList[index].vehicleNoif(dataList[index].state == 0) {content = '状态:0'+'</br>'+'编号:'+seatId}else if(dataList[index].state == 1) {content = '状态:1'+'</br>'+'编号:'+seatId+'</br>'+'车牌:'+vehicleNotipsTop = Number(sessionStorage.getItem('top'))+canvasInfo.top-90}else{content = '状态:2'+'</br>'+'编号:'+seatId+'</br>'+'车牌:'+vehicleNotipsTop = Number(sessionStorage.getItem('top'))+canvasInfo.top-90}//引入layer.tips提示框layui.use('layer', function(){var $ = layui.jquery,layer = layui.layer; // layer.tips(content, '#'+$(that)[0].id);layer.tips(content, '#'+dataList[index].seatId, {tips: [3, '#000000'],time: 0,success: function(layero, index) {//动态设置提示框位置layero.css('top',tipsTop+'px')layero.css('left',tipsLeft+'px')}});})}else{layer.closeAll()}
将多边形转换为矩形
将点击的坐标和所有的图形坐标一 一对比,判断点击坐标是否在图形内,在的话返回图形索引,不在返回-1
效果图
核心代码下载:canvas.js
提取码: n972