breep-Intersections

// Generating random lines and highlighting intersections
var boolDoRefresh;
var slider;
var totalLines;
 
 
function setup() {
  createCanvas(720, 480);
  background(255, 117, 102);
  boolDoRefresh = true;
  slider = createSlider(1, 100, 12)
  slider.position(10, 10)
}
 
function draw() {
 
 
  if (boolDoRefresh) {
    lines = [];
    background(255, 179, 102);
 
    for ( i = 0; i < slider.value(); i ++){
      var x1 = random(width);
      var x2 = random(width);
      var y1 = random(height);
      var y2 = random(height);
      lines[i] = [x1, y1, x2, y2] 
    }
 
    // Line intersections
    for ( i = 0; i < slider.value(); i++){
      for ( j = 0; j < slider.value(); j++){
 
 
         var intersection = findingIntersection(lines[i][0], lines[i][1], lines[i][2], lines[i][3], 
                                               lines[j][0], lines[j][1], lines[j][2], lines[j][3]); 
         if ( intersection != false) {
           stroke(0);
           fill(173, 216, 230);
           ellipse(intersection.x, intersection.y, 20, 20);
          }
         }
        }
 
 
    // Line drawing
    for (i = 0; i < slider.value(); i ++){
      strokeWeight(1);
      line( lines[i][0], lines[i][1], lines[i][2], lines[i][3])
    }
  fill(0);
  text(slider.value(), 150, 27)
  boolDoRefresh = false;
}
}
 
function mousePressed() {
  boolDoRefresh = true 
}
 
// Function implementation inspired by Paul Bourke's algorithm
// http://paulbourke.net/geometry/pointlineplane/function
// And implemented by Leo Bottaro
// http://paulbourke.net/geometry/pointlineplane/javascript.txt  
 
function findingIntersection(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}
}