casher-intersections

 

var boolDoRefresh = true;
var lines = [];
 
function setup() {
  createCanvas(720, 480);
}
 
function draw() {
  if (boolDoRefresh) {
 
    // set design values
    background(201, 239, 255);
    strokeWeight(1.5);
    stroke(140, 81, 200);
    lines = [];
 
    // assign random values to points of each line
    for (var k = 0; k < 12; k++) 
    {
      x1 = random(720);
      y1 = random(480);
      x2 = random(720);
      y2 = random(480);
      var newLine = [x1, y1, x2, y2];
      lines.push(newLine);
    }
 
    // double loop takes points from line[] to make a line
    // and forms an ellipse at the points from findIntersection()
    for (var i = 0; i < 12; i++)
    {
      for (var j = 0; j < 12; j++)
      {
        line(lines[i][0], lines[i][1], lines[i][2], lines[i][3])
        var steve = findIntersection(lines[i][0], lines[i][1], lines[i][2], lines[i][3], lines[j][0], lines[j][1], lines[j][2], lines[j][3])
 
        ellipse(steve[0],steve[1],20,20)
      }
    }
  }
	boolDoRefresh = false;
}
 
//adapted from Paul Bourkes/Leo Bottaro http://paulbourke.net/geometry/pointlineplane/javascript.txt
function findIntersection(x1, y1, x2, y2, x3, y3, x4, y4) {
 
  // Check if none of the lines are of length 0
	if ((x1 === x2 && y1 === y2) || (x3 === x4 && y3 === y4)) {
		return false
	}
 
	denominator = ((y4 - y3) * (x2 - x1) - (x4 - x3) * (y2 - y1))
 
  // Lines are parallel
	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
 
  // is the intersection along the segments
	if (ua < 0 || ua > 1 || ub < 0 || ub > 1) {
		return false
	}
 
  // Return a object with the x and y coordinates of the intersection
	let x = x1 + ua * (x2 - x1)
	let y = y1 + ua * (y2 - y1)
 
	return[x, y]
}
 
function mousePressed() {
  boolDoRefresh = true;
}