Interactive Intersections:
Intersections Gif:
function setup() { createCanvas(400, 400); } var boolDoRefresh; function setup() { createCanvas(400, 400); boolDoRefresh = true; } class Line { constructor(x1, y1, x2, y2){ this.x1 = x1; this.y1 = y1; this.x2 = x2; this.y2 = y2; } drawLine(){ line(this.x1,this.y1,this.x2,this.y2); } } function draw() { if (boolDoRefresh) { background(51); stroke(220); allLines=[]; intersectionCircles=[]; for (var k = 0; k < 12; k++) { var a = random(400); var b = random(400); var c = random(400); var d = random(400); var nLine= new Line(a,b,c,d); allLines.push(nLine); allLines[k].drawLine(); } for(var i=0; i<allLines.length-1; i++){ for(var j=1; j<allLines.length-2;j++){ if(allLines[i]!=allLines[j]) { var intersect= intersects(allLines[i].x1,allLines[i].y1,allLines[i].x2,allLines[i].y2,allLines[j].x1,allLines[j].y1,allLines[j].x2,allLines[j].y2); if (intersect!==false){ stroke(240,220,40); fill(240,220,40); ellipse(intersect.x,intersect.y,10,10); } } } } } boolDoRefresh = false } //formula from Paul Bourke function intersects(x1, y1, x2, y2, x3, y3, x4, y4) { if ((x1 === x2 && y1 === y2) || (x3 === x4 && y3 === y4)) { return false; } denominator = ((y4 - y3) * (x2 - x1) - (x4 - x3) * (y2 - y1)); if (denominator === 0) { return false; } let ua = ((x4 - x3) * (y1 - y3) - (y4 - y3) * (x1 - x3)) / denominator; let ub = ((x2 - x1) * (y1 - y3) - (y2 - y1) * (x1 - x3)) / denominator; if (ua < 0 || ua > 1 || ub < 0 || ub > 1) { return false } let x = x1 + ua * (x2 - x1) let y = y1 + ua * (y2 - y1) return {x, y} } function mousePressed() { boolDoRefresh = true; } |