xxxxxxxxxx
41
var x1 = -400, x2 = 400, x3 = 400,x4 = -400; // fixed ordered pairs
var cnt = 5; //counter to reset animation
function setup() {
createCanvas(400, 400); //create the canvas
background(60); //gray background
frameRate (10); //frame rate or speed
}
function draw() {
translate(width/2,width/2) //translate the canvas by half the width/height
stroke(70) //dark line color
strokeWeight(2);//thin lines
y1 = random(-400,400);//random y values:
y3 = random(-400,400);
y2 = random(-400,400);
y4 = random(-400,400);
findSolution() //call the solution function
//Only plot lines if the solution lies within the canvas:
if(xSoln>-200 && xSoln <200 && ySoln<200 && ySoln>-200){
line(x1,y1,x2,y2) //draw line
line(x3,y3,x4,y4) //draw line
}
//check cnt number to reset it when it hits 300
if(cnt > 300){
background(60);//reset canvas
cnt = 5;//reset counter
}
}
//function to find solution:
function findSolution(){
m1 = (y2-y1)/(x2-x1); //find slope1
m2 = (y3-y4)/(x3-x4);//find slope2
b1 = (y1-m1*x1);//find y-intercept1
b2 = (y3-m2*x3);//find y-intercept2
xSoln = (b1-b2)/(m2-m1);//find soln x value using substitution
ySoln = m1*xSoln+b1;//find soln y value by evaluating line equation with xSoln
fill(random(255),random(255),random(255)); //random color for circle
circle(xSoln,ySoln,cnt+1);//circle with size equal to count+5
circle(xSoln,ySoln,5);//small circle to denote solution
cnt=cnt+1;//increments counter for circles plotted
}