xxxxxxxxxx
let button;
let line1, line2;
function setup() {
createCanvas(400, 400);
button = createButton('Generate Lines');
button.position(10, height + 10);
button.mousePressed(generateLines);
generateLines();
}
function draw() {
background(220);
stroke(0);
if (line1 && line2) {
line(line1.x1, line1.y1, line1.x2, line1.y2);
line(line2.x1, line2.y1, line2.x2, line2.y2);
let intersection = findIntersection(line1, line2);
if (intersection) {
fill(255, 0, 0);
ellipse(intersection.x, intersection.y, 10, 10);
}
}
}
function generateLines() {
line1 = createRandomLine();
line2 = createRandomLine();
}
function createRandomLine() {
let x1 = random(width);
let y1 = random(height);
let x2 = random(width);
let y2 = random(height);
return { x1, y1, x2, y2 };
}
function findIntersection(l1, l2) {
let x1 = l1.x1;
let y1 = l1.y1;
let x2 = l1.x2;
let y2 = l1.y2;
let x3 = l2.x1;
let y3 = l2.y1;
let x4 = l2.x2;
let y4 = l2.y2;
let denominator = ((x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4));
if (denominator == 0) {
return null;
} else {
let px = ((x1 * y2 - y1 * x2) * (x3 - x4) - (x1 - x2) * (x3 * y4 - y3 * x4)) / denominator;
let py = ((x1 * y2 - y1 * x2) * (y3 - y4) - (y1 - y2) * (x3 * y4 - y3 * x4)) / denominator;
if (px >= 0 && px <= width && py >= 0 && py <= height) {
return createVector(px, py);
} else {
return null;
}
}
}