In [ ]:
from math import pi
from random import uniform

from ipywidgets import Button

from ipycanvas import Canvas, hold_canvas
In [ ]:
canvas = Canvas(width=800, height=600)
In [ ]:
def recursive_draw_leaf(canvas, length, r_angle, r_factor, l_angle, l_factor):
    canvas.stroke_line(0, 0, 0, -length)
    canvas.translate(0, -length)

    if length > 5 :
        canvas.save()

        canvas.rotate(r_angle)
        recursive_draw_leaf(canvas, length * r_factor, r_angle, r_factor, l_angle, l_factor)

        canvas.restore()

        canvas.save()

        canvas.rotate(l_angle)
        recursive_draw_leaf(canvas, length * l_factor, r_angle, r_factor, l_angle, l_factor)

        canvas.restore()
In [ ]:
def draw_tree(canvas):
    with hold_canvas(canvas):
        canvas.save()

        canvas.clear()

        canvas.translate(canvas.width / 2., canvas.height)

        canvas.stroke_style = 'black'

        r_factor = uniform(0.6, 0.8)
        l_factor = uniform(0.6, 0.8)

        r_angle = uniform(pi / 10., pi / 5.)
        l_angle = uniform(-pi / 5., -pi / 10.)

        recursive_draw_leaf(canvas, 150, r_angle, r_factor, l_angle, l_factor)

        canvas.restore()
In [ ]:
button = Button(description='Generate tree!')

def click_callback(*args, **kwargs):
    global canvas

    draw_tree(canvas)

button.on_click(click_callback)
In [ ]:
draw_tree(canvas)
In [ ]:
display(canvas)
display(button)

Acknowledgment:

This Notebook is adapted from a Notebook by Eric MADEC which was itself adapted from https://medium.com/better-programming/learning-p5-js-by-making-fractals-cbdcac5c651e