var boolDoRefresh; var numlines = 12; var length = 400; var lines = new Array(numlines); function setup() { createCanvas(720, 480); background(21, 62, 71); boolDoRefresh = true; } function draw() { if (boolDoRefresh) { //reset background background(21, 62, 71); stroke(24, 191, 179); //create lines for(var x = 0; x < numlines; x++) { var xstart = int(random(0, width)); var ystart = int(random(0, height)); var slope = random(0, 6.28); var xend = length*cos(slope) + xstart; var yend = length*sin(slope) + ystart; lines[x] = [xstart, ystart, xend, yend]; } //check intersections for(var l1 = numlines-1; l1 >=0; l1--) { var l2 = l1-1; while(l2 >= 0) { line1 = lines[l1]; line2 = lines[l2]; var cross = intersect(line1[0], line1[1], line1[2], line1[3], line2[0], line2[1], line2[2], line2[3]); if(cross != false) { fill(28, 229, 242); noStroke(); ellipse(cross.x, cross.y, 20, 20); } l2--; } } //draw lines { for(x = 0; x < numlines; x++) { stroke(24, 191, 179); line(lines[x][0], lines[x][1], lines[x][2], lines[x][3]); } } boolDoRefresh = false; } } // original calculation by Paul Bourke // Implementation by Leo Bottaro // http://paulbourke.net/geometry/pointlineplane/javascript.txt // Determine the intersection point of two line segments // Return FALSE if the lines don't intersect function intersect(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}; } function mousePressed() { boolDoRefresh = true; } |