mr-crocs-adventures/js/geometry/GeometryLine.js

55 lines
1.7 KiB
JavaScript

import GeometryPoint from "./GeometryPoint.js";
import GeometryStroke from "./GeometryStroke.js";
export default class GeometryLine
{
constructor(pointA, pointB)
{
this.pointA = pointA;
this.pointB = pointB;
}
getIntersectionWithLine(line)
{
try {
let xa = (line.pointB.x - line.pointA.x) * (this.pointB.x * this.pointA.y - this.pointA.x * this.pointB.y);
let xb = (this.pointB.x - this.pointA.x) * (line.pointB.x * line.pointA.y - line.pointA.x * line.pointB.y);
let xc = (line.pointB.y - line.pointA.y) * (this.pointB.x - this.pointA.x);
let xd = (this.pointB.y - this.pointA.y) * (line.pointB.x - line.pointA.x);
let x = (xa - xb) / (xc - xd);
if (isNaN(x)) {
return null;
}
let ya = (this.pointA.y - this.pointB.y) *(line.pointB.x * line.pointA.y - line.pointA.x * line.pointB.y);
let yb = (line.pointA.y - line.pointB.y) *(this.pointB.x * this.pointA.y - this.pointA.x * this.pointB.y);
let yc = (line.pointB.y - line.pointA.y) * (this.pointB.x - this.pointA.x);
let yd = (this.pointB.y - this.pointA.y) * (line.pointB.x - line.pointA.x);
let y = (ya - yb) / (yc - yd);
if (isNaN(y)) {
return null;
}
return new GeometryPoint(x, y);
} catch (error) {
return null;
}
}
getStroke()
{
return new GeometryStroke(this.pointA, this.pointB);
}
draw(context)
{
context.beginPath();
context.moveTo(this.pointA.x, this.pointA.y);
context.lineTo(this.pointB.x, this.pointB.y);
context.stroke();
}
}