Color examples

Draw RGB color table

size(200, 200)

w, h = 10, 10
x, y = 24, 18
s = 15

colorstep_r = 1.0 / (h-1)
colorstep_g = 1.0 / (w-1)
b = 0.5

for j in range(w):
    for i in range(h):
        g = j * colorstep_g
        r = i * colorstep_r
        fill(r, g, b)
        stroke(r, g, b)
        rect(x, y, s, s)
        translate(0, s)
    translate(s, -(s*h))

Draw CMYK color table

size(200, 200)

n, m = 10, 10
x, y = 24, 18
s = 13

colorstep_c = 1.0 / (n - 1)
colorstep_m = 1.0 / (m - 1)
Y = 0.5

for j in range(m):
    for i in range(n):

        M = j * colorstep_m
        C = i * colorstep_c
        cmykFill(C, M, Y, 0)
        cmykStroke(C, M, Y, 0)
        rect(x, y, s, s)
        translate(0, s)
    translate(s, -(s * n))

Color shadow example

# color shadow example

size(600, 600)

# save the current state
save()

# apply the shadow
shadow((17, -15), 20, (1, 0, 0))

# draw some objects
rect(94, 230, 178, 184)

font('Verdana Bold')
fontSize(70)
text('hello', (100, 100))

# disable the shadow
restore()

# draw something (no shadow)
oval(366, 318, 150, 150)

Draw random colors

# rectangles with random colors

translate(110, 112)

for i in range(10):
    fill(random(), random(), random(), 0.5)
    rect(0, 0, 416, 378)
    translate(38, 40)

Pick a random color from list

# create a list of colors
colors = [
    (1, 0, 0),
    (1, 1, 0),
    (0, 1, 0),
    (0, 1, 1),
    (0, 0, 1),
    (1, 0, 1),
]

# randomly choose a color from the list
color = choice(colors)
print color

# draw a square with this color
fill(*color)
rect(0, 0, width(), height())

Cycle through colors in list

# use division rest to cycle through colors

x, y = 0, 0
w, h = 20, 15
module = 20

# make colors
colors_amount = randint(5, 19)
colors = [(random(), random(), random()) for i in range(colors_amount)]

size(w*module, h*module)

# draw modules
count = 0
for i in range(h):
    save()
    for j in range(w):
        index = count % colors_amount
        color = colors[index]
        fill(*color)
        rect(0, 0, module, module)
        translate(module, 0)
        count += 1
    restore()
    translate(0, module)