rigatoni – Intersections01

via GIPHY

let redraw = true
function setup() {
  createCanvas(400, 400);
}
 
function draw() {
  if(redraw) {
  	background(180);
  	var lineArray = new LineArray(20)
  	lineArray.draw()
    redraw = false
  }
}
 
function mouseClicked() {
	redraw = true
}
 
// CLASS CONSTRUCTORS //
 
function LineArray(lineCount) {
	this.lines = []
  for(i=0; i<lineCount; i++) {
		this.lines[i] = new Line(random(width), random(width), random(width), random(width))
  }
 
  this.draw = function(displayIntersections=false) {
		for(i=0; i<lineCount; i++) {
			this.lines[i].draw()
      for(j=0; j<i; j++) {
				var intersection = getIntersection(this.lines[j], 
                                           this.lines[i])
        fill(0,0,0)
        if(isWithinSegment(intersection, this.lines[i]) &&
           isWithinSegment(intersection, this.lines[j])) {
        	ellipse(intersection[0], intersection[1], 5, 5)  
        }
      }
    }
  }
}
 
function Line(x1, y1, x2, y2) {
	this.x1=x1
  this.y1=y1
  this.x2=x2
  this.y2=y2
 
  this.draw = function() {
    stroke(5)
		line(this.x1, this.y1, this.x2, this.y2) 
  }
}
 
//HELPER METHODS //
 
// All the calculations here were informed by Paul Bourke's work
// http://paulbourke.net/geometry/pointlineplane/
function getIntersection(line1, line2) {
	var coef = (line2.x2-line2.x1)*(line1.y1-line2.y1)
  coef -= (line2.y2-line2.y1)*(line1.x1-line2.x1)
  var denom = (line2.y2-line2.y1)*(line1.x2-line1.x1)
  denom -= (line2.x2-line2.x1)*(line1.y2-line1.y1)
	coef = coef/denom
 
  var x = line1.x1 + coef*(line1.x2-line1.x1)
  var y = line1.y1 + coef*(line1.y2-line1.y1)
  var intersection = [x,y]
  return intersection
}
 
// I learnt how to do cross & dot products from here: 
// https://stackoverflow.com/questions/328107
// heavily based on the pseudocode written by user Cyrille Ka
function isWithinSegment(p, seg) {
	let x1 = min(seg.x1, seg.x2)
  let y1 = min(seg.y1, seg.y2)
  let x2 = max(seg.x1, seg.x2)
  let y2 = max(seg.y1, seg.y2)
 
  if((p[0]>=x1 && p[0]<=x2 && p[1]>=y1 && p[1]<=y2)==false) {
    return false
  }
  return true 
}