JSFiddle - React, Tailwind, and code Playground
by m1erickson
HTML
<h4>Drag a line to check intersection.</h4>
<canvas id="canvas" width=300 height=300></canvas>
CSS
body{ background-color: ivory; }
#canvas{border:1px solid red;}
JavaScript
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var $canvas = $("#canvas");
var canvasOffset = $canvas.offset();
var offsetX = canvasOffset.left;
var offsetY = canvasOffset.top;
var scrollX = $canvas.scrollLeft();
var scrollY = $canvas.scrollTop();
var isDown = false;
var startX = 0;
var startY = 0;
var mouseX = 25;
var mouseY = 25;
var rect = {
x: 100,
y: 100,
width: 100,
height: 100
};
var line = {
x1: 0,
y1: 0,
x2: 25,
y2: 25
};
draw();
function draw(isHit) {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
ctx.moveTo(startX, startY);
ctx.lineTo(mouseX, mouseY);
ctx.strokeStyle = "blue";
ctx.stroke();
ctx.strokeStyle = (isHit) ? "red" : "black";
ctx.strokeRect(rect.x, rect.y, rect.width, rect.height);
if (isHit) {
ctx.fillText("Intersects!", rect.x + rect.width / 2 - 25, rect.y + rect.height / 2);
}
}
// test line vs the 4 rectangle lines
function lineRectIntersects(line, rect) {
// p=line startpoint, p2=line endpoint
var p = {
x: line.x1,
y: line.y1
};
var p2 = {
x: line.x2,
y: line.y2
};
// top rect line
var q = {
x: rect.x,
y: rect.y
};
var q2 = {
x: rect.x + rect.width,
y: rect.y
};
if (doLineSegmentsIntersect(p, p2, q, q2)) {
return true;
}
// right rect line
var q = q2;
var q2 = {
x: rect.x + rect.width,
y: rect.y + rect.height
};
if (doLineSegmentsIntersect(p, p2, q, q2)) {
return true;
}
// bottom rect line
var q = q2;
var q2 = {
x: rect.x,
y: rect.y + rect.height
};
if (doLineSegmentsIntersect(p, p2, q, q2)) {
return true;
}
// left rect line
var q = q2;
var q2 = {
x: rect.x,
y: rect.y
};
if (doLineSegmentsIntersect(p, p2, q, q2)) {
return true;
}
...