Search code examples
pythonpyscript

how to do requestAnimationFrame in pyscript


from pyscript import document, window
from pyscript.ffi import create_proxy

class Canvas:
    def __init__(self, id, width=64*9, height=64*9):
        self.canvas = document.querySelector(id)
        self.ctx = self.canvas.getContext('2d')
        self.canvas.height = height
        self.canvas.width = width
        self.y = 100
        self.set_bg_color('black')
        self.animation()
    
    def clear(self, color='black', pos=(0,0), size=None):
        x,y = pos
        if size:
            width, height = size
        else:
            width, height = (self.canvas.width, self.canvas.height)
        self.ctx.fillStyle = color
        self.ctx.clearRect(x,y,width,height)
    
    def set_bg_color(self, color):
        
        self.ctx.fillStyle = color
        self.ctx.fillRect(0, 0, self.canvas.width, self.canvas.height)
    

    def animation(self):
        self.ctx.fillStyle = 'red'
        self.ctx.fillRect(100, self.y, 100, 100)
        self.y += 1
        self.clear()
        proxy = create_proxy(self.animation)
        window.requestAnimationFrame(proxy)

I get this error in pyscript

Uncaught PythonError: TypeError: Canvas.animation() takes 1 positional argument but 2 were given

I tried passing an event=None just in case but the canvas doesn't come up but no error


Solution

  • The requestAnimationFrame method in the browser passes a timestamp to the callback function. By default, your animation method is not set up to accept this argument.

    Try def animation(self, timestamp=none):.