You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PyScript中使用requestAnimationFrame出现参数错误及画布不显示问题求助

PyScript中使用requestAnimationFrame出现参数错误及画布不显示问题求助

问题原因分析

你遇到的第一个错误TypeError: Canvas.animation() takes 1 positional argument but 2 were given,是因为**window.requestAnimationFrame会自动向回调函数传递一个参数(当前的时间戳timestamp)**,而你的animation方法只定义了self这一个参数,导致参数不匹配。

当你尝试添加event=None后没有报错,但画布不显示,是因为代码的执行顺序逻辑错误:你先绘制了红色矩形,然后立刻调用clear()清空整个画布,刚画的内容被瞬间清除,自然看不到任何效果。

修正后的完整代码

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_proxy = create_proxy(self.animation)
        # 触发动画启动
        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)
    
    # 适配requestAnimationFrame自动传递的timestamp参数
    def animation(self, timestamp=None):
        # 1. 先清空上一帧的内容
        self.clear()
        # 2. 更新矩形的垂直位置
        self.y += 1
        # 可选:让矩形移出画布后重置位置,实现循环动画
        if self.y > self.canvas.height:
            self.y = 0
        # 3. 绘制当前帧的红色矩形
        self.ctx.fillStyle = 'red'
        self.ctx.fillRect(100, self.y, 100, 100)
        # 4. 调度下一帧动画
        window.requestAnimationFrame(self.animation_proxy)

# 实例化Canvas(需确保HTML中有对应id的canvas元素,如<canvas id="my-canvas"></canvas>)
canvas = Canvas("#my-canvas")

关键修改点说明

  1. 参数适配:
    给animation方法添加timestamp=None参数,接收requestAnimationFrame自动传递的时间戳,彻底解决参数不匹配的错误。

  2. 调整绘制逻辑顺序:
    将clear()移到最前面执行,先清空上一帧内容,再更新坐标、绘制当前帧,确保每次绘制的内容能被看到。

  3. 优化代理创建:
    在初始化时仅创建一次代理并保存为实例属性,避免每次调用animation都重复创建代理,减少不必要的资源消耗。

  4. 可选循环动画优化:
    添加了self.y的重置逻辑,让矩形移出画布后回到顶部,实现循环动画效果(可根据需求选择保留或删除)。

额外注意事项

  • 确保HTML页面中存在对应id的canvas元素,例如:<canvas id="my-canvas"></canvas>,否则document.querySelector无法找到目标元素,后续操作会失败。

备注:内容来源于stack exchange,提问作者Michael

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.15 09:38:03