JavaScript新手开发谷歌恐龙小游戏遇绘制问题:恐龙与仙人掌不显示
我是JavaScript新手,正在开发一款简易谷歌恐龙小游戏,但遇到恐龙和仙人掌均无法显示的问题。打开HTML文件的实时服务器进入游戏窗口后,通过开发者工具排查发现,错误出现在update()函数中使用context.drawImage的代码行。相关代码如下:
//dino velocityY += gravity; //velocity of jumping upwards weighed down with gravity dino.y = Math.min(dino.y + velocityY, dinoY); // applies gravity to current dino.y, so that dino doesn't exceed ground level context.drawImage(dinoImg, dino.x, dino.y, dino.width, dino.height); //cactus for (let i = 0; i <= cactusArray.length; i++) { cactusArray[i].x += velocityX; context.drawImage(cactusArray[i].img, cactusArray[i].x, cactusArray[i].y, cactusArray[i].width, cactusArray[i].height); if (detectCollision(dino, cactusArray[i])) { gameOver = true; dinoImg.src = "./img/dino-dead.png"; dinoImg.onload = function() { context.drawImage(dinoImg, dino.x, dino.y, dino.width, dino.height); } } }
我已确认所有图片放置路径正确,且在context.drawImage前添加console.log("Dino image loaded")未输出日志,推测问题出在图片加载或路径环节。
强制图片预加载后再启动游戏:如果
update()在图片加载完成前就执行,drawImage会因图片未就绪失败,后续的log也不会触发。必须确保所有图片加载完成后再启动游戏循环:// 预加载所有需要的图片 const imageList = [ { key: 'dino', path: './img/dino.png' }, { key: 'cactus', path: './img/cactus.png' }, { key: 'dinoDead', path: './img/dino-dead.png' } ]; const loadedImages = {}; let loadCount = 0; imageList.forEach(item => { const img = new Image(); img.src = item.path; img.onload = () => { loadCount++; loadedImages[item.key] = img; // 所有图片加载完成后初始化游戏 if (loadCount === imageList.length) { startGame(); // 这里放初始化游戏、启动循环的代码 } }; img.onerror = () => { console.error(`图片加载失败:${item.path}`); }; });修复循环边界错误:你的仙人掌循环条件是
i <= cactusArray.length,数组索引从0开始,这个条件会导致最后一次访问cactusArray[cactusArray.length](该位置为undefined),调用drawImage时直接报错,中断整个update()函数,恐龙的绘制也会被打断。把条件改成:for (let i = 0; i < cactusArray.length; i++) { // 原循环内代码 }排查图片加载的真实错误:通过
onerror事件打印错误,能直接定位路径问题——比如大小写不匹配(系统区分大小写时,./img/Dino.png和./img/dino.png是不同路径)、文件后缀错误(实际是.jpg却写成.png)等。验证canvas上下文有效性:确保
context是通过canvas.getContext('2d')正确获取的,没有返回null。可以在初始化时添加console.log(context)确认。
内容的提问来源于stack exchange,提问作者Elias Castilla

