color
The default color space in Processing is RGB/255. This means that a color is built by adding the red, green, and blue channels together, which can each have a value between 0 and 255. A color is built using the color(red, green, blue) function. We can also call color(val) with a single parameter, which is either interpreted as a greyscale value if it's between 0 and 255, or as an RGB value if it's greater than 255. Note that you can use the hexadecimal notation anywhere you would use an int.
The following two statements are identical:
// grey color(128, 128, 128); color(128);
The following two statements are also identical:
// orange color(255, 128, 64); color(#FF8040);
You can change the color space used (RGB or HSB) by calling colorMode(mode). When you do this, the three parameters of the color functions are interpreted as hue, saturation, and value. You can also change the range per channel using the colorMode(mode, range) function. The following statements are identical:
// grey color(128); colorMode(RGB, 1.0); color(0.5); colorMode(RGB, 100); color(50);
transparency
You can always add an extra parameter when creating a color to set the alpha (transparency). This applies to color(), fill(), and stroke(), but NOT background().
This is useful for blending colors:
// draw a red circle fill(1.0, 0, 0, 0.5); ellipse(125, 125, 100, 100); // draw a green circle fill(0, 1.0, 0, 0.5); ellipse(150, 175, 100, 100); // draw a blue circle fill(0, 0, 1.0, 0.5); ellipse(175, 125, 100, 100);
It is also useful for creating a motion blur effect. This is done by replacing the background() by a semi-transparent rect() covering the entire canvas. Let's do this in our star example.
void setup() {
size(400, 400);
smooth();
noStroke();
}
void draw() {
// draw a semi-transparent rect to cover the whole canvas
// this will give the stars that "fading" effect
fill(0, 10);
rect(0, 0, width, height);
// draw a star at the current mouse position with size relative to the mouse movement
fill(216, 61, 4);
int avgMove = int((abs(pmouseX-mouseX)+abs(pmouseY-mouseY))/2);
drawStar(mouseX, mouseY, avgMove*5);
}
void drawStar(int xPos, int yPos, int starSize) {
beginShape();
vertex(xPos, yPos-starSize/2);
vertex(xPos-starSize/3, yPos+starSize/2);
vertex(xPos+starSize/2, yPos-starSize/8);
vertex(xPos-starSize/2, yPos-starSize/8);
vertex(xPos+starSize/3, yPos+starSize/2);
vertex(xPos, yPos-starSize/2);
endShape();
}