thabir – Intersections
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 | //Credit to Paul Bourke for the math behind this algorithm //Credit to Joyce for the idea of drawing the circles behind the lines var num_Lines = 12; var line_Length = 250; var lines = []; var intersections; function calculateIntersections(i) { for(var j=0; j<i; j++) { var x1 = lines[i][0]; var y1 = lines[i][1]; var x2 = lines[i][2]; var y2 = lines[i][3]; var x3 = lines[j][0]; var y3 = lines[j][1]; var x4 = lines[j][2]; var y4 = lines[j][3]; var denom = ((y4 - y3)*(x2 - x1)) - ((x4 - x3)*(y2 - y1)); var u1num = ((x4 - x3)*(y1 - y3)) - ((y4 - y3)*(x1 - x3)); var u2num = ((x2 - x1)*(y1 - y3)) - ((y2 - y1)*(x1 - x3)); if(denom!=0 && u1num!=0 && u2num!=0) { var u1 = (u1num*1.0) / denom; var u2 = (u2num*1.0) / denom; if(0<=u1 && u1<=1 && 0<=u2 && u2<=1) { var x = round(x1 + (u1*(x2 - x1))); var y = round(y1 + (u1*(y2 - y1))); intersections = append(intersections, x); intersections = append(intersections, y); } } } } function drawLinesAndCircles() { strokeWeight(1.5); fill(50, 255, 255, 50); for(var i=0; i<intersections.length; i+=2) { ellipse(intersections[i], intersections[i+1], 30, 30); } for(var i=0; i<num_Lines; i++) { line(lines[i][0], lines[i][1], lines[i][2], lines[i][3]); } } function generateRandomLines() { intersections = []; for(var i=0; i<num_Lines; i++) { lines[i] = []; lines[i][0] = floor(random(720)); lines[i][1] = floor(random(480)); do { var angle = radians(random(360)); lines[i][2] = round(cos(angle)*line_Length) + lines[i][0]; lines[i][3] = round(sin(angle)*line_Length) + lines[i][1]; } while(0>lines[i][2] || lines[i][2]>720 || 0>lines[i][3] || lines[i][3]>480); calculateIntersections(i); } } function setup() { createCanvas(720, 480); background(255, 245, 245); generateRandomLines(); drawLinesAndCircles(); } function draw(){ background(255, 245, 245); drawLinesAndCircles(); } function mousePressed() { background(255, 245, 245); generateRandomLines(); drawLinesAndCircles(); } |