Tuesday, January 27, 2009

Bezier Curves

The following is from an interactive program I wrote to generate Bezier curves. The first click of the mouse draws a point. The second click draws a parametric line. The third click draws a Quadratic Bezier curve, the fourth click draws a Cubic Bezier curve, and the fifth click clears the screen and starts all over again.

Click the picture below open up the application in a new page:




Here is the code:

int pointNum=0;
int x0=0;
int y0=0;
int x1=0;
int y1=0;
int x2=0;
int y2=0;

void setup() {
size(400, 400);
stroke(255);
background(192, 64, 0);
}

void mouseReleased(){
if (pointNum==0){
x0=mouseX;
y0=mouseY;
point(x0,y0);
pointNum=1;
println("point0");

}
else if (pointNum==1){
paraLine(x0,y0,mouseX,mouseY);
x1=mouseX;
y1=mouseY;
pointNum=2;
println("point1");
}
else if (pointNum==2){
background(192, 64, 0);
quadBez(x0,y0,x1,y1,mouseX,mouseY);
x2=mouseX;
y2=mouseY;
pointNum=3;
}
else if(pointNum==3){
background(192, 64, 0);
cubBez(x0,y0,x1,y1,x2,y2,mouseX,mouseY);
pointNum=4;
}
else{
background(192, 64, 0);
pointNum=0;
}

}

void paraLine(int x0,int y0,int x1,int y1){
float x=0;
float y=0;
for(float t=0; t<=1; t=t+.001) { x=x0+(t*(x1-x0)); y=y0+(t*(y1-y0)); point(int(x),int(y)); } } void quadBez(int x0,int y0,int x1,int y1, int x2, int y2){ float x=0; float y=0; for(float t=0; t<=1; t=t+.001) { x=(pow((1-t),2)*x0)+(2*(1-t)*(t*x1))+(pow(t,2)*x2); y=(pow((1-t),2)*y0)+(2*(1-t)*(t*y1))+(pow(t,2)*y2); point(int(x),int(y)); } } void cubBez(int x0,int y0,int x1,int y1, int x2, int y2, int x3, int y3){ float x=0; float y=0; for(float t=0; t<=1; t=t+.001) { x=(pow((1-t),3)*x0)+(3*(pow((1-t), 2))*(t*x1))+(3*(1-t)*(pow(t,2)*x2))+(x3*pow(t,3)); y=(pow((1-t),3)*y0)+(3*(pow((1-t), 2))*(t*y1))+(3*(1-t)*(pow(t,2)*y2))+(y3*pow(t,3)); point(int(x),int(y)); } }

No comments:

Post a Comment