P5 library - Colors

Greyscale colors

...

...

from p5 import * def setup(): size(300, 300) background(191) # light grey fill(255) # white stroke(0) # black stroke_weight(10) circle(width / 2, height / 2, width * 0.75) run()

Named colors

...

...

from p5 import * def setup(): size(300, 300) background("lightskyblue") fill("mediumorchid") stroke("teal") stroke_weight(10) circle(width / 2, height / 2, width * 0.75) run()

RGB colors

...

...

...

from p5 import * def setup(): size(300, 300) color_mode(RGB) # THIS LINE IS OPTIONAL, RGB MODE IS THE DEFAULT background(212, 247, 212) # or "#D4F7D4", some light green fill(85, 158, 84) # or "#559E54", some dark green stroke(154, 7, 148) # or "#9A0794", some purple stroke_weight(10) circle(width / 2, height / 2, width * 0.75) run()

HSB colors

...

...

...

...

...

from p5 import * def setup(): size(300, 300) color_mode(HSB) # DO NOT FORGET THIS LINE background(212, 247, 212) # some blue fill(85, 158, 84) # some green stroke(154, 7, 148) # some white stroke_weight(10) circle(width / 2, height / 2, width * 0.75) run()

Transparency (alpha = opacity)

...

...

...

from p5 import * from math import cos def setup(): size(350, 350) def draw(): background(240) no_stroke() # Trunk (opaque) fill("brown") rect(width * 0.4, height / 4, width * 0.2, height) # Leaves (opaque) fill("green") circle(width / 2, height / 2, width * 0.75) # Apples (opacity changes with time) alpha = map(cos(radians(frame_count)), -1, +1, 0, 255) fill(255, 0, 0, alpha) # <=== WE USE TRANSPARENCY HERE circle(width / 2, height / 2, 25) circle(175, 88, 25) circle(251, 131, 25) circle(251, 219, 25) circle(175, 263, 25) circle(99, 219, 25) circle(99, 131, 25) # Text fill(0) text(f"Alpha = {int(alpha)}", 10, 10) run()

Check a pixel's color

get(x, y) returns an object representing the color of the pixel at coordinates (x, y). This object has the following properties:

Here is a sample program:

from p5 import * def setup(): size(300, 300) background("salmon") color = get(width / 2, height / 2) print(f" hex: {color.hex}") print(f" rgb: {color.red}, {color.green}, {color.blue}") print(f" hsb: {color.hue:.0f}, {color.saturation:.0f}, {color.brightness:.0f}") print(f"alpha: {color.alpha}") run() # OUTPUT: # ====== # hex: #FA8072 # rgb: 250, 128, 114 # hsb: 6, 93, 98 # alpha: 255

Checking a pixel's color is used mainly for games and you can see an example in P5 library - Interactivity.