The formula for calculating the speed of the mouse’s horizontal motion is the absolute value of the difference between mouseX and pmouseX. The absolute value of a number is defined as that number without its sign:
- The absolute value of –2 is 2.
- The absolute value of 2 is 2.
- abs(mouseX – pmouseX)
// Learning Processing
// Daniel Shiffman
// http://www.learningprocessing.com
void setup() {
size(200, 200);
background(255);
smooth();
}
void draw() {
stroke(0);
strokeWeight(abs(pmouseX - mouseX));
line(pmouseX, pmouseY, mouseX, mouseY);
}









I was interested to see the solution for this, I arrived the same solution printed but I thought that there may be a way to get the stroke width operating on the Y axis too. I tried to make the strokewidth the total of abs(pmouseX – mouseX) and abs(pmouseY – mouseY) then dividing this by figure 2 to get the average…no joy! I’m not yet proficient enough to know where my error is!
Comment by Abdul — August 26, 2009 @ 8:38 am
That’s right, try this!
strokeWeight((abs(pmouseX – mouseX) + abs(pmouseY-mouseY))/2);
Comment by admin — August 26, 2009 @ 6:10 pm
Thanks that was really helpful, (I think I got a little muddled my parenthesis before) – spot the punn!
Comment by Abdul — August 30, 2009 @ 9:28 am
How can someone do the opposite?The slower the mouse moves the wider the drawn line ?
Comment by Lalaios — November 1, 2009 @ 2:39 pm
You can use the map() function to map a range that goes from 0-10 to, say, 10-0. You can also do this with simple math of course:
int x = 10 – x;
if x is 0, x becomes 10, if x is 2, x becomes 8, etc.
You have to watch out though b/c you can’t have a strokeWeight of less than 0. Here is some code to start with:
Comment by admin — November 2, 2009 @ 11:34 am
How about this one?
float thickness = sqrt(sq(pmouseX-mouseX)+sq(pmouseY-mouseY));
strokeWeight(thickness);
line(pmouseX, pmouseY, mouseX, mouseY);
Of course this then can be modified like this to invert the behaviour:
float thickness = 10 / sqrt(sq(pmouseX-mouseX)+sq(pmouseY-mouseY));
Comment by Nils — December 31, 2009 @ 1:14 pm
how about this :
(it seems to work, though i havent really read up the if and else functions)
void setup() { size(1000,500); background(0); // line repeating drawing smooth(); stroke(225); } void draw() { float a = abs(pmouseX-mouseX); // specifying a variablle to set limits to if (a >10) { // limit set strokeWeight(50); // max thickness } else { strokeWeight (a); // variable within limit } line(pmouseX,pmouseY,mouseX,mouseY); }Comment by meto — March 9, 2010 @ 12:55 pm