Canvas. Отследить нажатие мыши по грани полигона
Имеется следующий код на React
const [dots, setDots] = useState<any>({
zone: {
coords: [],
},
})
const drawPoly = (poly: any, color: string) => {
contextRef.current!.fillStyle = 'rgba(100,100,100,0)'
contextRef.current!.lineWidth = 1
contextRef.current!.strokeStyle = color
contextRef.current?.beginPath()
contextRef.current?.moveTo(poly[0][0], poly[0][1])
for (let i = 1; i < poly.length; i++) {
contextRef.current?.lineTo(poly[i][0], poly[i][1])
}
contextRef.current?.closePath()
contextRef.current?.fill()
contextRef.current?.stroke()
}
const drawPoint = (coords: any, color: string) => {
contextRef.current!.lineJoin = 'round'
contextRef.current!.lineWidth = 5
contextRef.current!.strokeStyle = color
for (let i = 0; i < coords.length; i++) {
contextRef.current!.beginPath()
contextRef.current!.arc(
coords[i][0],
coords[i][1],
3,
0,
2 * Math.PI,
false
)
contextRef.current!.fillStyle = color
contextRef.current!.fill()
contextRef.current!.lineWidth = 5
contextRef.current!.stroke()
}
}
const setPoint = (e: React.MouseEvent<HTMLCanvasElement>): void => {
const bounding = canvasRef.current?.getBoundingClientRect()
setDots((prev: any) => ({
...prev,
coords: [
...prev.coords,
[
e.clientX - bounding!.left,
e.clientY - bounding!.top,
],
}))
}
const drawPolygons = () => {
for (let key in dots) {
if (dots[key].coords.length) {
drawPoint(dots[key].coords, '#fff')
drawPoly(dots[key].coords, '#fff')
}
}
}
useEffect(() => {
if (dots[key].coords.length) {
drawPolygons()
}
}, [dots, drawPolygons])
return (
<canvas ref={canvasRef} onClick={setPoint}></canvas>
)
Я приложил его в сокращенном варианте, при необходимости дополню. Суть компонента: при нажатии на canvas, вызывается функция setPoint, которая записывает координаты в стейт dots. При изменении dots вызывается функция drawPolygons, которая отрисовывает полигон, циклично вызывая функции drawPoly и drawPoint. В результате получается полигон, отрисованный по поставленным нами точкам.
Проблема: мне нужно отследить нажатие именно по грани отрисованного полигона и получить точки, между которыми проведена линия. Я пробовал добавить функцию, которая будет проверять принадлежность поставленной точки к полигону, но это совсем не то, что мне нужно. Есть ли какие-то способы проверить, нажали ли мы конкретно на грань полигона или нет?