If you are a Python person, you’ll feel at home and enjoy all HTML5 features with PySketch!
Check this famous flappy bird game done in pysketch.
Get Started: Bouncing Logo
We’ll learn the basics by doing a bouncing logo sketch covering the essential points. It’s the most known screen saver, and it’ll be fun to build it here. Here is the final sketch, feel free to play with code and run.
Let’s take a closer look at the code:
from browser import document, window
browser.html is a wrapper module for HTML tags. It allows us to create and manipulate dom elements with ease in Python. For all other tags and examples, please check here.
canvas = CANVAS(width=width, height=height)
Here, we create a canvas element and add it to the body of the HTML page.
ctx is the context of the canvas where we do our drawing operations. We are not going into detail on canvas API, but you can get more info here.
logo = IMG(src ='logo.png')
Files are loaded asynchronously, which means that the image is not available on the following line and will take some time to load. So we set an
onload callback here. Once the logo is loaded, our app will start looping. We’ll come to the looping part later.
PySketch provides cloud hosting for assets to be able to use in sketches. Go to Sketch Details -> Files tab and upload your assets for your sketch.
Sketch assets can be loaded by their filenames, as seen in the code snippet above.
This is the main draw function, and it calculates the new position by taking speed into account and renders the logo in the canvas context. Please read inline comments on the final sketch to get the idea of drawing on context.
This is the heart of most graphical apps. It refers to the overall flow of the program and keeps looping infinitely until manually stopped. Browsers have built-in
requestAnimationFrame function. It’s designed to run smooth animations on the browser without blocking the page. Your animation function is called before the browser performs the next repaint. The number of callbacks is usually 60 times per second if you request a new frame.
In this loop, we call the
draw function, and after drawing, we request a new frame recursively. This process repeats forever until we stop the app.
How is the Python being run by the browser?