Статья по теме:
Демо JavaScript:
Поставьте 4 точки левой кнопкой мыши, чтобы определить отрезки
<html> <head> <meta charset="UTF-8"/> <title>Определение точки пересечения отрезков</title> <script src="main.js"></script> </head> <body > <canvas id="paint" width="503" height="503"></canvas> </body> </html>
var ctx; var idA; var x,y; let points1 = []; var A,B,C; var pointxx,pointyy; window.onload=function(){ //по нажатию левой кнопки мыши ставятся точки document.getElementById('paint').addEventListener('click', (e) => { if(points1.length < 4) points1.push({x: e.offsetX, y: e.offsetY}); Init(); }); } function Init() { ctx = document.getElementById("paint").getContext('2d'); ctx.fillStyle = "#ffffff"; ctx.strokeStyle = "#2e49cd"; ctx.fillRect(0, 0, 503, 503); ctx.fillStyle = "#2e49cd"; for(let i = 0; i < points1.length; i++) ctx.fillRect(points1[i].x - 2, points1[i].y - 2, 4, 4); if(points1.length > 1) ctx.beginPath(); ctx.moveTo(points1[0].x, points1[0].y); ctx.lineTo(points1[1].x, points1[1].y); ctx.stroke(); ctx.closePath(); if(points1.length > 3) { ctx.beginPath(); ctx.moveTo(points1[2].x, points1[2].y); ctx.lineTo(points1[3].x, points1[3].y); ctx.stroke(); ctx.closePath(); TempCheck(); } } function VEK(ax,ay,bx,by)//векторное произведение { return ax*by-bx*ay; } function CrossingCheck(p1,p2,p3,p4) //проверка пересечения { var v1,v2,v3,v4; v1=VEK(p4.x - p3.x, p4.y - p3.y, p1.x - p3.x, p1.y - p3.y); v2=VEK(p4.x - p3.x, p4.y - p3.y, p2.x - p3.x, p2.y - p3.y); v3=VEK(p2.x - p1.x, p2.y - p1.y, p3.x - p1.x, p3.y - p1.y); v4=VEK(p2.x - p1.x, p2.y - p1.y, p4.x - p1.x, p4.y - p1.y); if(v1*v2<0 && v3*v4<0) return true; else return false; } function EquationOfTheLine(p1,p2) //построение уравнения прямой Ax+By+C { // var A,B,C; A=p2.y-p1.y; B=p1.x-p2.x; C=-p1.x*(p2.y-p1.y)+p1.y*(p2.x-p1.x); } function IntersectionX(a1,b1,c1,a2,b2,c2)// поиск точки пересечения по Х { var d,dx,pointx; d=a1*b2-b1*a2; dx=-c1*b2+b1*c2; pointx=dx/d; return pointx; } function IntersectionY(a1,b1,c1,a2,b2,c2) //поиск точки пересечения по Y { var d,dy,pointy; d=a1*b2-b1*a2; dy=-a1*c2+c1*a2; pointy=dy/d; return pointy; } function TempCheck()// проверка отрезков на пересечение { ctx.fillStyle = "red"; if(CrossingCheck(points1[0],points1[1],points1[2],points1[3])) { var a1,b1,c1,a2,b2,c2; EquationOfTheLine(points1[0],points1[1]); a1=A;b1=B;c1=C; EquationOfTheLine(points1[2],points1[3]); a2=A;b2=B;c2=C; pointxx=IntersectionX(a1,b1,c1,a2,b2,c2); pointyy=IntersectionY(a1,b1,c1,a2,b2,c2); ctx.fillRect(pointxx - 2, pointyy - 2, 4, 4); setTimeout(function() {alert('Отрезки пересекаются в точке Х=' +pointxx+ ', Y=' +pointyy);},100); } else{ setTimeout(function() {alert("Отрезки Не пересекаются");},100); } }