const
ctx = document.querySelector('#scene').getContext('2d'),
polygons = [
[ [8, 57], [15, 57], [15, 71], [8, 71], [8, 57] ], // no
[ [20, 25], [35, 25], [35, 50], [20, 50], [20, 25] ], // yes
[ [77, 36], [85, 36], [85, 50], [77, 50], [77, 36] ], // no
[ [80, 70], [86, 70], [86, 80], [80, 80], [80, 70] ], // yes
],
line = [ [8, 5], [92, 78] ];
const main = () => {
ctx.translate(0.5, 0.5);
polygons.forEach(polygon => {
const collided = isCollision(polygon, line);
ctx.strokeStyle = collided ? 'red' : 'blue';
ctx.fillStyle = collided ? 'pink' : 'lightblue';
drawPolygon(ctx, polygon);
ctx.fill();
});
ctx.strokeStyle = 'red';
drawLine(ctx, line);
};
const lineLine = (x1, y1, x2, y2, x3, y3, x4, y4) => {
let uA = ((x4-x3)*(y1-y3) - (y4-y3)*(x1-x3)) / ((y4-y3)*(x2-x1) - (x4-x3)*(y2-y1));
let uB = ((x2-x1)*(y1-y3) - (y2-y1)*(x1-x3)) / ((y4-y3)*(x2-x1) - (x4-x3)*(y2-y1));
return (uA >= 0 && uA <= 1 && uB >= 0 && uB <= 1);
}
const polyLine = (vertices, x1, y1, x2, y2) => {
let next = 0;
for (let current = 0; current < vertices.length; current++) {
next = current+1;
if (next == vertices.length) next = 0;
let x3 = vertices[current][0];
let y3 = vertices[current][1];
let x4 = vertices[next][0];
let y4 = vertices[next][1];
let hit = lineLine(x1, y1, x2, y2, x3, y3, x4, y4);
if (hit) return true;
}
return false;
}
const isCollision = (polygon, line) =>
polyLine(polygon, line[0][0], line[0][1], line[1][0], line[1][1]);
const drawPolygon = (ctx, points) => {
ctx.beginPath();
ctx.moveTo(points[0][0], points[0][1]);
for (let i = 1; i < points.length - 1; i++) {
ctx.lineTo(points[i][0], points[i][1]);
}
ctx.closePath();
ctx.stroke();
};
const drawLine = (ctx, points) => {
ctx.beginPath();
ctx.moveTo(points[0][0], points[0][1]);
ctx.lineTo(points[1][0], points[1][1]);
ctx.stroke();
};
main();
<canvas id="scene"></canvas>