Skip to content

Instantly share code, notes, and snippets.

@qexat
Last active June 15, 2023 09:21
Show Gist options
  • Save qexat/97409294d5f1d5514ccbb43c720ce448 to your computer and use it in GitHub Desktop.
Save qexat/97409294d5f1d5514ccbb43c720ce448 to your computer and use it in GitHub Desktop.
pycanvas example
#!/usr/bin/env python3
import pycanvas
# We need this global constant to get the mouse position
WINDOW = pycanvas.get_window()
@pycanvas.init
async def init(canvas: pycanvas.Canvas):
"""
Canvas initialization function.
It is only called once, before `loop`.
This is similar to p5's `setup`, except that the `pycanvas.init()`
decorator already creates the canvas for us.
"""
# Equivalent to canvas.set_size(width=1920, height=1080, unit="px")
# but `set_size` does not have fine-granulated unit picking
canvas.set_width(1920, "px")
canvas.set_height(1080, "px")
# Defaults to white which could be fine for this example
# but this allows to show how to set the canvas background
canvas.set_background(pycanvas.UniformFill(255, 198, 127)) # pale orange (#FFC67F)
@pycanvas.loop(refresh=True, exit_key="\x1b")
async def loop(canvas: pycanvas.Canvas, pen: pycanvas.Pen): # pen = canvas.pen
"""
Canvas draw function.
It is called indefinitely, after `init`.
It stops if `Ctrl+C` is pressed, or if the `exit_key` is detected in the stdin.
Resembles p5's `draw`, with the same difference than `init`.
`pen` argument is a shortcut for `canvas.pen`.
"""
# Resetting the canvas so we only see the current mouse pos
canvas.reset()
# The pen does not write anything yet
pen.lift()
# Originally `mouse_x` and `mouse_y` were descriptors but the cost of getting
# the mouse position is too big on most platforms to fit in so there are methods now
pen.move(WINDOW.mouse_x(), WINDOW.mouse_y())
# Sets the pen to black ; UniformFill() because it could be a gradient or image
pen.set_color(pycanvas.UniformFill(0, 0, 0))
# By default, the size is 10 which is a bit too small
pen.set_size(30)
# The pen writes a small dot where the mouse is
pen.put_down()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment