var lines = 12;
var intersects = 0;
var lineArray = [];
var intersectArray = [];
function setup() {
createCanvas(720, 480);
colorMode(HSB);
background(20, 10, 220);
var x1, x2, y1, y2;
for (var i = 0; i < lines; i++) {
x1 = 0; y1 = 0; x2 = 0; y2 = 0;
append(lineArray, [x1, y1, x2, y2]);
}
}
function draw() {
var x1, x2, y1, y2;
var x, y;
for(var i = 0; i<intersects; i++){
x = intersectArray[i][0];
y = intersectArray[i][1];
stroke(10, 50, 150);
fill(10, 50, 150);
ellipse(x, y, 10, 10);
}
for (var i = 0; i < lines; i++) {
x1 = lineArray[i][0];
y1 = lineArray[i][1];
x2 = lineArray[i][2];
y2 = lineArray[i][3];
stroke(0, 0, 0);
fill(0, 0, 0);
line(x1, y1, x2, y2);
}
}
function mouseClicked() {
var x1, x2, y1, y2;
intersects = 0;
intersectArray = [];
colorMode(HSB);
background(20, 10, 220);
for (var i = 0; i < lines; i++) {
x1 = random(0, width);
y1 = random(0, height);
x2 = random(0, width);
y2 = random(0, height);
lineArray[i][0] = x1;
lineArray[i][1] = y1;
lineArray[i][2] = x2;
lineArray[i][3] = y2;
}
drawIntersect();
}
function drawIntersect(){
var px, py, L1, L2;
var x1,x2,x3,x4,y1,y2,y3,y4;
for(var i = 0; i < lines; i++){
for(var j = i+1; j < lines; j++){ L1 = lineArray[i]; L2 = lineArray[j]; x1 = L1[0]; y1 = L1[1]; x2 = L1[2]; y2 = L1[3]; x3 = L2[0]; y3 = L2[1]; x4 = L2[2]; y4 = L2[3]; var ua = ((x4-x3)*(y1-y3)-(y4-y3)*(x1-x3))/ ((y4-y3)*(x2-x1)-(y2-y1)*(x4-x3)); var ub = ((x2-x1)*(y1-y3)-(y2-y1)*(x1-x3))/ ((y4-y3)*(x2-x1)-(y2-y1)*(x4-x3)); if(ua>0 && ua<1 && ub>0 && ub<1){
px = x1+ua*(x2-x1);
py = y1+ua*(y2-y1);
}
append(intersectArray, [px,py]);
intersects++;
}
}
} |