With our latest Processing sketch it’s time to play with the mouse, and the keyboard as well. I mean, we can’t just leave out the keyboard!
This one is simple, just drawing a box, and using the ‘r’, ‘g’, and ‘b’ keys, you can change the color. You can also hit ‘q’ to blank the canvas and start over.
We use width/2, height/2 for proper centering of our box. Also, you’ll see that all the real action happens when you click and drag the mouse. Once you start doing that, you can press the r, g, or b key to change the color.
/* * 20110513.pde */ void setup() { size(800, 600); noFill(); strokeWeight(1); stroke(255,0,0); background(0); } void draw() { if(keyPressed) { if (key == 'r' || key == 'R') { stroke(255,0,0); } if (key == 'g' || key == 'G') { stroke(0,255,0); } if (key == 'b' || key == 'B') { stroke(0,0,255); } if (key == 'q' || key == 'Q') { background(0); } } } void mouseDragged() { rectMode(CENTER); rect(width/2, height/2, mouseX, mouseY); }