Introduction

If you are familiar with using the Canvas with JavaScript, then you will quickly know how to draw on the Canvas with Python knowing a couple of minor items. If you are a Python developer new to drawing inside a browser, the example in this article will show you the basics. This example is the classic clock. Credit goes to W3 Schools for the source code that I ported to Python for this example.

The key to drawing graphics in the browser is the Canvas API [link]. I will not go into detail as there are many excellent articles on the Internet. The code should help understand what the Python interfaces are. I find it a lot easier to understand an API when I can play with working code.

The first item is to declare a region to draw within using the tag <canvas>. This tag sets the size, location, and background of the canvas. There are many more attributes [link].

This example creates a 300×300 canvas to draw in:

Next, you need to get a handle and context to the canvas:

Let’s say that you want to write a green box on the canvas:

Pyscript Example

Clock Example

The primary function to review is drawClock. This function does three things every second:

  • Draws the clock face
  • Draws the numbers on the clock face
  • Draws the hands of time

Complete Example

More Information

Photography Credit

I write free articles about technology. Recently, I learned about Pexels.com which provides free images. The image in this article is courtesy of Pixabay at Pexels.