aahdee-Intersections

 

 
//defining constants
const WIDTH = 720;
const HEIGHT = 480;
const BACK_COLOR = 'rgb(172, 230, 230)';
const NUM_LINES = 100;
const LINE_LEN = 250;
const LINE_COLOR = 'rgb(0, 86, 86)';
const LINE_STROKE = 2;
const CIR_CIR = 12;
const CIR_COLOR = 'rgba(11, 140, 140, 0.5)';
 
//global variables
var pointList = [];
var intsecList = [];
 
function setup() 
{
	createCanvas(WIDTH, HEIGHT);
	background(BACK_COLOR);
	angleMode(DEGREES);
}
 
/* Lines functions.
   These are created by generating a random start point and slope and then uses trig 
	 to get the end points from that data.*/
 
function drawLine() 
{
  stroke(LINE_COLOR);
	strokeWeight(LINE_STROKE);
	var x1 = random(50, WIDTH-50);
	var y1 = random(50, HEIGHT-50);
	var angle = random(360);
	var endHeight = LINE_LEN*sin(angle);
	var endLength = LINE_LEN*cos(angle);
	var x2 = x1 + endLength;
	var y2 = y1 + endHeight;
	line(x1,y1,x2,y2);  
	var linePoint = [x1,y1,x2,y2];
	pointList.push(linePoint);
}	
 
//source for intersect formulas: http://paulbourke.net/geometry/pointlineplane/
function grabIntersects(points)
{
  var x1 = points[0], y1 = points[1],
  		x2 = points[2], y2 = points[3],
      x3 = points[4], y3 = points[5],
      x4 = points[6], y4 = points[7];
  var den = ((y4-y3)*(x2-x1)) - ((x4-x3)*(y2-y1));
	if (den != 0)
	{
		var ua = (((x4-x3)*(y1-y3))-((y4-y3)*(x1-x3)))/den;
    var ub = (((x2-x1)*(y1-y3))-((y2-y1)*(x1-x3)))/den;
    if (0 <= ua && ua <= 1 && 0 <= ub && ub <= 1)
    {
			var x = x1 + ua*(x2-x1);
      var y = y1 + ua*(y2-y1);
			intsecList.push([x,y]);
    }
	}
}	
 
function drawCircles()
{
  noStroke();
  fill(CIR_COLOR);
	while (intsecList.length != 0)
	{
		var points = intsecList.shift();
		ellipse(points[0], points[1], CIR_CIR);
	}
}
 
function draw() 
{
	setup();
	for (var i = 0; i < NUM_LINES; i++)
	{
		drawLine();
		for (var j = 0; j < pointList.length-1; j++)
		{ 
      grabIntersects(pointList[j].concat(pointList[pointList.length-1]));
		}
	}
	drawCircles();
  pointList = [];
	intsecList = [];
  noLoop();
}
 
function mouseClicked()
{
	redraw();
}