creatyde-Intersections

Behold, the Intersections application!

Take a look at this handy gif for the best user experience:

 

Here is the code I used to create the Intersections project:

var n = 100; // number of lines
var length = 300;
var windowLength = 720;
var widnowHeight = 480;
var radius = 20;

function getLine(x, y, angle) {
	// compute halfways
	var distX = sin(angle) * length/2;
	var distY = cos(angle) * length/2;
	return [x - distX, y - distY, x + distX, y + distY];
}

// using Paul Bourke's methodology
function intersection(x1,y1, x2,y2, x3,y3, x4,y4) {
	// find denominator
	var sd = (y4 - y3)*(x2 - x1)-(x4 - x3)*(y2 - y1);
	if (sd == 0) return [-1, -1];
	var sn = (x4 - x3)*(y1 - y3)-(y4 - y3)*(x1 - x3);
	var s = sn/sd;
 	// first intersection point
	var x = x1 + s*(x2 - x1);
	var y = y1 + s*(y2 - y1);
	// determine if point is within bounds (using x)
	// not using y because sin/cos work weirdly for it
	if (x >= x1 && x <= x2 && x >= x3 && x <= x4)
		return [x, y];
	// no intersection
	return [-1, -1];
}
	
function click() {
	// reset background
	background('#fff2f2');
	// save lines
	var lineArray = [];
	// generate n random lines, each of length 2 inches (black)
	for (var i = 0; i < n; i++) {
		var angle = random(0, PI);
		var x = random(0, windowLength);
		var y = random(0, windowHeight);
		var l = getLine(x, y, angle);
		append(lineArray, l);
	}
	// draw intersections
	fill(255, 150, 150, 50);
	strokeWeight(0);
	for (var i = 0; i < n; i++) {
		var line1 = lineArray[i];
		for (var j = i+1; j < n; j++) { 
			var line2 = lineArray[j]; 
			var inter = intersection(line1[0], line1[1], 
				line1[2], line1[3], line2[0], 
				line2[1], line2[2], line2[3]); 
			if (inter[0] > -1) 
				ellipse(inter[0], inter[1], radius);
		}
	}
	// draw lines
	strokeWeight(2);
	for (var i = 0; i < n; i++) {
		var l = lineArray[i];
		line(l[0], l[1], l[2], l[3]);
	}
	// done
}

function draw() { 
	if (mouseIsPressed) click();
}

function setup() {
	createCanvas(windowLength, windowHeight);
  	background('#fff2f2');
	stroke('#000000');
}