JavaScript游戏开发遇TypeError:无法读取undefined的'x'属性求助
问题解决:Cannot read properties of undefined (reading 'x')
错误信息
index.js:20 Uncaught TypeError: Cannot read properties of undefined (reading 'x')
at Sprite.draw (index.js:20:40)
at animate (index.js:47:13)
问题根源
代码里存在多处拼写错误,将position误写为positon或postion,导致Sprite实例的位置属性无法被正确访问,进而抛出“读取undefined的x属性”的错误。具体出错点:
- Sprite类的draw方法中:
this.positon.x、this.postion.y→ 正确拼写为this.position.x、this.position.y - 创建background实例时:
postion: {x:-300, y:-450}→ 正确拼写为position - animate函数中:
background.positon.y→ 正确拼写为background.position.y - Sprite构造函数的参数:
positon→ 正确拼写为position
修复后的完整代码
const canvas = document.querySelector('canvas') const c = canvas.getContext('2d') canvas.width = 1024; canvas.height = 576; c.fillStyle = 'white' c.fillRect(0, 0, canvas.width, canvas.height) const image = new Image() image.src = './img/kazimon-map.png' const playerImage = new Image() playerImage.src = './img/playerDown.png' class Sprite { constructor({ position, velocity, image }) { this.position = position this.image = image } draw() { c.drawImage(this.image, this.position.x, this.position.y) } } const background = new Sprite({ position: { x:-300, y:-450 }, image: image }) const keys = { w: { pressed: false }, a: { pressed: false }, s: { pressed: false }, d: { pressed: false } } function animate() { window.requestAnimationFrame(animate) background.draw() c.drawImage( playerImage, 0, 0, playerImage.width / 4, playerImage.height, canvas.width / 2 - (playerImage.width / 4) /2, canvas.height / 2 - playerImage.height / 2, playerImage.width / 4, playerImage.height, ) if (keys.w.pressed) { background.position.y = background.position.y - 3 } } animate() window.addEventListener('keydown', (e) => { switch (e.key) { case 'w': keys.w.pressed = true console.log(keys.s.pressed) break case 'a': keys.a.pressed = true console.log(keys.s.pressed) break case 's': keys.s.pressed = true console.log(keys.s.pressed) break case 'd': keys.d.pressed = true console.log(keys.s.pressed) break default: console.log(keys) } })
额外说明:原keydown事件的switch语句中,console.log(keys)未被包含在任何case分支内,已移至default分支下避免语法错误。
内容的提问来源于stack exchange,提问作者Kbeast
相关产品推荐
相关产品推荐

