调用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
相关产品推荐
相关产品推荐

