Intersection of 2 lines
by Simon Hi
HTML
<h1>Intersection of 2 lines</h1>
<p>Coordinates between 0 and 1000</p>
<h2>Line 1</h2>
<div>
<label>xa1 :<input type="text" value="200"></label>
<label>ya1 :<input type="text" value="200"></label>
</div>
<div>
<label>xb1 :<input type="text" value="400"></label>
<label>yb1 :<input type="text" value="400"></label>
</div>
<h2>Line 2</h2>
<div>
<label>xa2 :<input type="text" value="200"></label>
<label>ya2 :<input type="text" value="400"></label>
</div>
<div>
<label>xb2 :<input type="text" value="400"></label>
<label>yb2 :<input type="text" value="200"></label>
</div>
<button onclick="magic()">Run</button>
<div>Solution : <span></span></div>
<canvas width="1000" height="1000"></canvas>
CSS
button {
margin: 1rem 0;
}
canvas {
display: block;
background: #ccf;
width: 20em;
max-width: 100%;
}
JavaScript
var xa1, ya1, xb1, yb1, xa2, ya2, xb2, yb2;
function intersection(xa1, ya1, xb1, yb1, xa2, ya2, xb2, yb2) {
var a1, b1, a2, b2, x, y;
if (xb1 == xa1) {
x = xa1;
if (xb2 == xa2) {
alert("No solution!");
return {
x: 0,
y: 0
};
}
a2 = (yb2 - ya2) / (xb2 - xa2);
b2 = ya2 - a2 * xa2;
y = a2 * xa1 + b2;
} else if (xb2 == xa2) {
a1 = (yb1 - ya1) / (xb1 - xa1);
b1 = ya1 - a1 * xa1;
x = xa2;
y = a1 * xa2 + b1;
} else {
a1 = (yb1 - ya1) / (xb1 - xa1);
b1 = ya1 - a1 * xa1;
a2 = (yb2 - ya2) / (xb2 - xa2);
b2 = ya2 - a2 * xa2;
x = (b2 - b1) / (a1 - a2);
y = a1 * (b2 - b1) / (a1 - a2) + b1;
}
return {
x: x,
y: y
};
}
function draw() {
var cn = document.querySelector("canvas");
var cx = cn.getContext("2d");
cx.clearRect(0, 0, cn.width, cn.height);
cx.beginPath();
cx.moveTo(xa1, ya1);
cx.lineTo(xb1, yb1);
cx.stroke();
cx.moveTo(xa2, ya2);
cx.lineTo(xb2, yb2);
cx.stroke();
}
function magic() {
var p;
xa1 = parseInt(document.querySelector("div:nth-of-type(1) label:nth-of-type(1) input").value, 10);
ya1 = parseInt(document.querySelector("div:nth-of-type(1) label:nth-of-type(2) input").value, 10);
xb1 = parseInt(document.querySelector("div:nth-of-type(2) label:nth-of-type(1) input").value, 10);
yb1 = parseInt(document.querySelector("div:nth-of-type(2) label:nth-of-type(2) input").value, 10);
xa2 = parseInt(document.querySelector("div:nth-of-type(3) label:nth-of-type(1) input").value, 10);
ya2 = parseInt(document.querySelector("div:nth-of-type(3) label:nth-of-type(2) input").value, 10);
xb2 = parseInt(document.querySelector("div:nth-of-type(4) label:nth-of-type(1) input").value, 10);
yb2 = parseInt(document.querySelector("div:nth-of-type(4) label:nth-of-type(2) input").value, 10);
p = intersection(xa1, ya1, xb1, yb1, xa2, ya2, xb2, yb2);
document.querySelector("span").innerHTML = "(" + p.x + "," + p.y + ")";
draw();
}