Hi,
I have been playing around with the beginings of a drawing project and have tried to code up something that feels and acts quite close to 'real' drawing.
The main problems with this I found were the rate with which the mouse/tablet date comes in. That is, when the cursor is not moving much you get a lot of unnecessary points and when it is moving fast you get too few points and thus ugly kinks.
When there are too many points I just ignore them until the cursor has moved N pixels away. And when there are not enough points I use the curve() function to smooth the lines. This has the downside of always being a frame behind as it need the latest XY as guides - but maybe there is a workaround for that.
So I just wanted to offer up my code for anyone to have a play with and possibly make some suggestions about more efficient or effective ways of doing this.
Cheers!
Quote:
int[] xx = new int[4];
int[] yy = new int[4];
int inc = 0;
int now;
// Minimum space between points
int space = 5;
// When to start smoothing the lines
int curving = 7;
void setup() {
size(800, 600);
background(255);
noFill();
stroke(0);
strokeWeight(1);
smooth();
cursor(CROSS);
noLoop();
}
//
void draw() {
}
void mousePressed() {
stroke(0);
xx[0] = mouseX;
yy[0] = mouseY;
inc = 1;
}
void mouseDragged() {
now = inc % 4;
// When there have been 4 sets of points inputted...
if (inc < 4){
xx[now] = mouseX;
yy[now] = mouseY;
if(inc < 3) {
// Draw the first section with straight lines
line(mouseX, mouseY, pmouseX, pmouseY);
}
redraw();
inc++;
} else {
// Calculate the movement since the last point was added
int movement = abs(mouseX - xx[3]) + abs(mouseY - yy[3]);
// If there is movement then draw another point
if(movement > space) {
// Shift the array values over for the next curve and add the new mouseXY
xx[0] = xx[1];
xx[1] = xx[2];
xx[2] = xx[3];
xx[3] = mouseX;
yy[0] = yy[1];
yy[1] = yy[2];
yy[2] = yy[3];
yy[3] = mouseY;
if (movement > curving) {
// When there is more movement (and thus fewer points) smooth the line to avoid kinks
stroke(0);
curve(xx[0], yy[0], xx[1], yy[1], xx[2], yy[2], xx[3], yy[3]);
} else {
// Draw normal point to point line when movement is slow
//stroke(150);
line(xx[1], yy[1], xx[2], yy[2]);
}
redraw();
inc++;
}
}
}
void mouseReleased() {
// Draw the last section as a straight line and not a curve
line(xx[2], yy[2], xx[3], yy[3]);
redraw();
inc = 0;
}
void keyReleased() {
switch(keyCode){
case BACKSPACE:
case DELETE:
background(255);
redraw();
break;
}
}