一个画布上画多个duo边形,点击画布上的一点,判断哪个多边形被选中。
该方法在如果点击的点再多边形的边缘位置,判断不准确。
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>绘图</title>
<style>
.container {
position: relative;
}
#myImg {
position: absolute;
top: 0;
left: 0;
z-index: 1;
}
#myCanvas {
position: absolute;
top: 0;
left: 0;
z-index: 5;
border: 1px solid #f00;
}
</style>
<script type="text/javascript">
window.onload = function () {
var arrBox = [
{ pointArr: [{ x: 100, y: 100 }, { x: 100, y: 300 }, { x: 300, y: 600 }, { x: 100, y: 100 }], maxX: 0, maxY: 0, minX: 0, minY: 0 },
{ pointArr: [{ x: 200, y: 100 }, { x: 200, y: 300 }, { x: 20, y: 500 }, { x: 200, y: 100 }], maxX: 0, maxY: 0, minX: 0, minY: 0 },
{ pointArr: [{ x: 300, y: 300 }, { x: 500, y: 300 }, { x: 600, y: 700 }, { x: 550, y: 650 }, { x: 450, y: 700 },{ x: 500, y: 600 },{ x: 400, y: 700 },{ x: 300, y: 300 }], maxX: 0, maxY: 0, minX: 0, minY: 0 },
]
var arr = [{ x: 100, y: 100 }, { x: 100, y: 300 }, { x: 300, y: 500 }, { x: 100, y: 100 },]
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
//被点击的多边形的下标存储在arrOk
var testX, testy, arrOk = [];
arrBox.map((arr, index) => {
arr.minX = (arr.pointArr)[0].x, arr.minY = (arr.pointArr)[0].y
for (var i = 0; i < arr.pointArr.length; i++) {
if (i == 0) {
context.beginPath()
context.moveTo((arr.pointArr)[i].x, (arr.pointArr)[i].y);
} else if (i == arr.length) {
context.moveTo((arr.pointArr)[i].x, (arr.pointArr)[i].y);
context.strokeStyle = "#f00";
context.stroke();
context.save()
} else {
context.lineTo((arr.pointArr)[i].x, (arr.pointArr)[i].y);
context.strokeStyle = "#f00";
context.stroke();
}
if (arr.maxX < (arr.pointArr)[i].x) { arr.maxX = (arr.pointArr)[i].x }
if (arr.maxY < (arr.pointArr)[i].y) { arr.maxY = (arr.pointArr)[i].y }
if (arr.minX > (arr.pointArr)[i].x) { arr.minX = (arr.pointArr)[i].x }
if (arr.minY > (arr.pointArr)[i].y) { arr.minY = (arr.pointArr)[i].y }
}
})
canvas.onmousedown = function (e) {
var e = e || window.event;
// 获取鼠标相对canvas的坐标
testX = e.pageX - this.offsetLeft;
testy = e.pageY - this.offsetTop;
arrBox.map((arr, index) => {
console.log('for循环22', arr, testy, testX)
if (testX < arr.minX || testX > arr.maxX || testy < arr.minY || testy > arr.maxY) {
// 测试不guo
return false
} else {
console.log('通过了', index, i)
}
for (var i = 0; i < arr.pointArr.length; i++) {
var whereOk = pnpoly(arr.pointArr.length, arr.pointArr, testX, testy)
function pnpoly(nvert, vert, testx, testy) {
var i, j, c = 0;
for (i = 0, j = nvert - 1; i < nvert; j = i++) {
if (((vert[i].y > testy) != (vert[j].y > testy)) && (testx < (vert[j].x - (vert[i]).x) * (testy - vert[i].y) / (vert[j].y - vert[i].y) + vert[i].x)) {
c = !c;
}
}
return c;
}
console.log('whereOk', whereOk)
if (whereOk) {
arrOk.push(index)
}
}
})
}
}
</script>
</head>
<body>
<div class='container'>
<canvas id="myCanvas" width="1000" height="1000">
您的浏览器暂不支持画布!
</canvas>
</div>
</body>
</html>