PySketch documentation

  • Introduction
    • Getting Started
    • Loading Assets
  • Tutorials
    • Drawing Basics
    • Bouncing Logo
    • Circle Game
Theme by the Executable Book Project

Bouncing Logo

Bouncing Logo#

In this tutorial, we’ll explore asset loading basics and animating them in your sketch by doing well known bouncing logo example.

You can see and play with final sketch here.

PySketch allows assets hosting for files that you want to use in your sketch and you can use these assets by their uploaded filenames. We’ll skip the canvas creating part and dive into the asset loading part since we already cover that in the previous tutorial. Once you have uploaded your assets from Details tab, you can use them in your sketch as in the following code.

logo = IMG(src ='logo.png')
logo.onload = lambda e: loop(0)

IMG is the img HTML element and we load the logo image by setting the src attribute. Loading file is asynchronous process and images won’t be available immediately on the next line. We need to set a callback function, so once image is loaded, our lambda function will start looping application.

Rest of the code is almost the same as in the previous tutorial. In the draw function, we linearly change our logo’s position and once it reaches the end of the screen, we reverse its direction. At he end we draw logo image with drawImage function.

def draw():
   ...

   # Update position of the logo
   x += x_speed
   y += y_speed

   # Reversing x speed if logo goes beyond of the canvas width.
   if x + logo.naturalWidth >= width:
      x_speed = -x_speed
      x = width - logo.naturalWidth
   elif x <= 0:
      x_speed = -x_speed
      x = 0

   # Reversing y speed if logo goes beyond of the canvas height.
   if y + logo.naturalHeight >= height:
      y_speed = -y_speed
      y = height - logo.naturalHeight
   elif y <= 0:
      y_speed = -y_speed
      y = 0

   # Drawing logo here
   ctx.drawImage(logo, x, y)

previous

Drawing Basics

next

Circle Game

© Copyright 2022, pysketch.com.