JSFiddle - React, Tailwind, and code Playground
HTML
<canvas id="myCanvas"></canvas>
CSS
#myCanvas {
width: 200px;
height: 200px;
}
JavaScript
var c = document.getElementById("myCanvas"),
ctx = c.getContext("2d"),
lines = [{
x1: 25,
y1: 85,
x2: 50,
y2: 15
}, {
x1: 80,
y1: 10,
x2: 150,
y2: 105
}];
c.width = 200;
c.height = 200;
function draw(cx, cy) {
ctx.clearRect(0, 0, c.width, c.height);
lines.forEach(function(line) {
ctx.beginPath();
ctx.moveTo(line.x1, line.y1);
ctx.lineTo(line.x2, line.y2);
if (lineCircleIntersects(line.x1, line.y1, line.x2, line.y2, cx, cy, 5))
ctx.strokeStyle = "red";
else
ctx.strokeStyle = "black";
ctx.stroke();
});
console.log(ctx.strokeStyle);
}
draw(0,0);
function lineCircleIntersects(x1, y1, x2, y2, cx, cy, cr) {
var dx = x2 - x1,
dy = y2 - y1,
a = dx * dx + dy * dy,
b = 2 * (dx * (x1 - cx) + dy * (y1 - cy)),
c = cx * cx + cy * cy,
bb4ac;
c += x1 * x1 + y1 * y1;
c -= 2 * (cx * x1 + cy * y1);
c -= cr * cr;
bb4ac = b * b - 4 * a * c;
return bb4ac >= 0; // true: collision, false: no collision
}
$("#myCanvas").on("mousemove", function(e){
draw(e.offsetX, e.offsetY);
});