DEV Community

Brooke Myers for Anvil

Posted on • Originally published at anvil.works

Decorating a Virtual Cookie with Python and Canvas

This post is part of the Anvil Advent calendar. We're building one web app a day for 24 days, using nothing but Python!
 
For Day 7, I built a web app using the Canvas API to decorate a mess-free, no-bake virtual Christmas cookie. And I didn't need to use any HTML, JavaScript or CSS.

You can check out the app here and decorate your own cookie.

Screenshot of app

This was my first attempt at using Canvas. Here's how I built the cookie elements and the web app using Anvil and Python:

Making lots of circles

Virtual cookie with a snowman

My simple cookie decorations are built from circles and triangles of different sizes and colors. By building more elements, the app could easily be extended to have more options or be more complicated.

Because my app makes extensive use of circles, I first defined a function to draw a circle. The function takes in the desired x and y coordinates of the circle and its radius as arguments:

def draw_circle(self, x, y, radius):
    c = self.canvas_1
    c.begin_path()
    c.arc(x, y, radius, 0, 2 * math.pi)
    c.close_path()
Enter fullscreen mode Exit fullscreen mode

This function is called when the form opens to create the cookie base. It’s also used to make the frosting, sprinkles and snowman.

Adding random sprinkles

The x and y coordinates for the sprinkles are chosen randomly each time the sprinkles_button is clicked:

import random

...

def sprinkles_button_click(self, **event_args):
"""This method is called when the button is clicked"""
    color = self.color_dropdown.selected_value
    if color is None:
    color = "#e62325" #defaults to red
    self.canvas_1.fill_style = color

    x_list = list(range(400, 600))
    x_list = random.sample(x_list, 15)

    y_list = list(range(100, 300))
    y_list = random.sample(y_list, 15)

    for x,y in zip(x_list, y_list):
        self.draw_circle(x, y, 6)
        self.canvas_1.fill()
Enter fullscreen mode Exit fullscreen mode

Christmas tree triangles

For the Christmas tree, I just made three overlapping green triangles that get progressively smaller as they move up the y-axis. The following code draws one triangle:

c = self.canvas_1

c.fill_style = '#00884b'

c.begin_path()
c.move_to(410,280)     
c.line_to(590,280)
c.line_to(500,170)
c.close_path()
c.fill()
Enter fullscreen mode Exit fullscreen mode

P.S. You can check out all of our Advent Calendar apps here.

Top comments (0)