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

调用clearRect触发Uncaught TypeError错误,求排查解决

问题解决

第一个关键问题:setInterval 里的 this 指向跑偏了

你在Game类的构造函数里写了setInterval(this.update, 20),这里的坑在于:setInterval调用回调时,默认会把this绑定到全局对象(浏览器里就是window),而不是你的Game实例。所以当update函数执行时,里面的this根本不是你创建的game对象,this.context自然就是undefined,这就是报错的根源。

修复方式二选一:

  • 用箭头函数保留this指向(推荐写法):
this.interval = setInterval(() => this.update(), 20)
  • 手动绑定this:
this.interval = setInterval(this.update.bind(this), 20)

第二个关键问题:drawComponent 传参错了

在update方法里调用component.drawComponent(context)时,这里的context是个未声明的变量,应该传入当前Game实例的this.context:

component.drawComponent(this.context)

修复后的完整代码

class Game {
    constructor(canvas_width, canvas_height) {
        this.canvas = document.createElement("canvas")
        this.canvas.width = canvas_width
        this.canvas.height = canvas_height

        this.context = this.canvas.getContext("2d")

        document.body.insertBefore(this.canvas, document.body.childNodes[0])

        // 修复this指向
        this.interval = setInterval(() => this.update(), 20)

        this.components = []
    }

    update() {
        this.context.clearRect(0, 0,  this.canvas.width, this.canvas.height)
        this.components.forEach(component => {
            component.updateComponent()
            // 修复传参
            component.drawComponent(this.context)
        });
    }
}

class GameComponent {
    constructor(x, y, width, height, color) {
        this.x = x
        this.y = y
        this.width = width
        this.height = height
        this.color = color
    }

    updateComponent() {
        
    }

    drawComponent(context) {
        context.fillStyle = this.color
        context.fillRect(this.x, this.y, this.width, this.height)
    }
}

var game = new Game(780, 350)
var rect = new GameComponent(50, 50, 64, 64, "#000055")
game.components.push(rect)

内容的提问来源于stack exchange,提问作者danilwhale

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 22:02:04