Drawing Basics#

In this tutorial, we will learn drawing basics and how to animate a circle by using Canvas API. If you already familiar with canvas in JavaScript, we’ll do the same thing just by using Python.

You can see and play with final sketch here.

We’ll start by importing the required modules. window and document modules are equivalent to JavaScript versions. We access to global variables and functions via window object. And we access to the DOM via document object. CANVAS is a HTML element that we use to draw on.

from browser import document, window
from browser.html import CANVAS

As default we only have an empty html page. We need to create and add a canvas element to it. Canvas is initially blank. To display something, we need to get contex object to obtain the rendering context and its drawing functions.

canvas = CANVAS(width=400, height=400)
document.body.appendChild(canvas)

ctx = canvas.getContext('2d')

Now we ready to draw something. We have two functions draw and loop. draw function contains all the drawing code. loop function is called every time the browser redraws the page.

Let’s take a look at the draw function below. We start by filling background color. We set the fill color with fillStyle property and use fillRect function to fill a rectangle. We animate the circle by changing the x position. We use beginPath function to start a new path. We use arc function to draw a circle. We use fill function to fill the circle.

def draw():
   global x

   ctx.fillStyle = 'white'
   ctx.fillRect(0, 0, 400, 400)

   x += 1
   if x > 450:
      x = -50

   ctx.fillStyle = 'grey'
   ctx.beginPath();
   ctx.arc(x, 200, 50, 0, 2 * 3.14);
   ctx.fill()

Now it’s time to start the animation. In thew loop function we first draw our scene. Then we call requestAnimationFrame function. It’s a built-in function in the JavaScript. It tells the browser that you wish to perform an animation and requests that the browser calls our loop before the next repaint. This creates an infinite loop and runs our animation until we stop it.

def loop():
   draw()
   window.requestAnimationFrame(loop)

loop()

We have learned how to draw and animatime on a canvas by using Python. You can also see the other simple scanline example here to explore more.