tyvan-Intersections
Using objects to hold lines and points was a fun exercise. If I were to re-code this project, I would draw the lines in a separate function, so they intersect above the pink dots.
var numLines = 12; var dia = 20; var xOne, yOne, xTwo, yTwo; var lines = []; var inters = []; // Properties related to whole document function setup() { createCanvas(720, 480); noLoop(); ellipseMode(CENTER); } // Starts the first session function draw() { mousePressed(); } // Refreshes everything on click function mousePressed() { background(235, 254, 240); lines = []; inters = []; for(i = 0; i < numLines; i++) { generateLine(); } drawLines(); } // Places x, y coordinates into matrix function generateLine(){ var line = { x1: random(width), y1: random(height), x2: random(width), y2: random(height), } lines.push(line); } function drawLines() { // Iterates through matrix of coordinates for(i = 0; i < numLines; i++){ var x1 = lines[i].x1; var y1 = lines[i].y1; var x2 = lines[i].x2; var y2 = lines[i].y2; for(j = 0; j < numLines; j++){ var x3 = lines[j].x1; var y3 = lines[j].y1; var x4 = lines[j].x2; var y4 = lines[j].y2; LineIntersect( x1, y1, x2, y2, x3, y3, x4, y4); } strokeWeight(1); line(x1, y1, x2, y2); } for(i = 0; i < inters.length; i++){ mx = inters[i][0]; my = inters[i][1]; strokeWeight(0); fill(255, 220, 220, 200); ellipse(mx, my, dia, dia); } } // Function adapted from Paule Bourke // http://paulbourke.net/geometry/pointlineplane/pdb.c function LineIntersect (x1, y1, x2, y2, x3, y3, x4, y4) { var mua,mub; var denom,numera,numerb; var tru; denom = (y4-y3) * (x2-x1) - (x4-x3) * (y2-y1); numera = (x4-x3) * (y1-y3) - (y4-y3) * (x1-x3); numerb = (x2-x1) * (y1-y3) - (y2-y1) * (x1-x3); var mx; var my; if (abs(denom) > 0){ /* Is the intersection along the segments */ mua = numera / denom; mub = numerb / denom; if (mua < 0 || mua > 1 || mub < 0 || mub > 1) { return; } else { mx = x1 + mua * (x2 - x1); my = y1 + mua * (y2 - y1); inters.push([mx, my]); } } } |