Patterns

Create pattern from an Image object

In [ ]:
from ipycanvas import Canvas
from ipywidgets import Image

The pattern source is a small image that will get repeated on the Canvas

In [ ]:
Image.from_file('pattern.png')
In [ ]:
canvas = Canvas()
pattern = canvas.create_pattern(Image.from_file('pattern.png'))
canvas.fill_style = pattern
canvas.fill_rect(0, 0, canvas.width, canvas.height)
canvas

Create pattern from another Canvas

In [ ]:
from math import pi

from ipycanvas import Canvas
In [ ]:
pattern_source = Canvas(width=50, height=50)

pattern_source.fill_style = '#fec'
pattern_source.fill_rect(0, 0, 50, 50)
pattern_source.stroke_arc(0, 0, 50, 0, .5 * pi)

pattern_source
In [ ]:
canvas2 = Canvas()
pattern1 = canvas2.create_pattern(pattern_source)
canvas2.fill_style = pattern1
canvas2.fill_rect(0, 0, canvas2.width, canvas2.height)
canvas2
In [ ]:
pattern_source = Canvas(width=50, height=50)

pattern_source.fill_style = '#338ac4'
pattern_source.fill_rect(0, 0, 50, 50)

pattern_source.fill_style = '#3341c4'
pattern_source.fill_circle(50, 50, 5)
pattern_source.fill_circle(0, 0, 5)
pattern_source.fill_circle(50, 0, 5)
pattern_source.fill_circle(0, 50, 5)

pattern_source.fill_style = '#33c4b5'
pattern_source.fill_circle(25, 25, 10)
pattern_source
In [ ]:
canvas = Canvas()
pattern2 = canvas.create_pattern(pattern_source)
canvas.fill_style = pattern2
canvas.fill_rect(0, 0, canvas.width, canvas.height)
canvas

You can even combine patterns

In [ ]:
canvas = Canvas()

canvas.fill_style = pattern1
canvas.fill_rect(0, 0, canvas.width, canvas.height)

canvas.fill_style = pattern2
canvas.fill_circle(canvas.width / 2., canvas.height / 2., 100)

canvas