Vanilla JS Canvas游戏中fillText不生效问题求助
解决Canvas游戏中GameOver文本不显示与Promo触发失效问题
核心问题分析
你遇到的两个问题本质都是animate循环的逻辑顺序错误,导致关键绘制函数要么没被持续调用,要么调用时机不对:
- 游戏结束后animate循环直接停止,
drawGameOver只执行一次就被中断,或者被后续的clearRect覆盖 - 得分超过20的判断没有放在animate循环的渲染阶段,导致
drawPromo从未触发
具体修复方案
1. 调整animate循环的状态判断逻辑
确保游戏结束后,循环仍持续运行,只渲染GameOver界面,不再执行游戏更新逻辑:
function animate() { // 先判断游戏状态,结束时直接渲染GameOver并保持循环 if (gameOver) { drawGameOver(); requestAnimationFrame(animate); return; } // 正常游戏流程:清屏→更新状态→渲染元素 ctx.clearRect(0, 0, canvas.width, canvas.height); // 更新大理石位置、碰撞检测等原有逻辑 marbles.forEach((marble, index) => { marble.x -= marble.speed; // 游戏结束条件:大理石移出左边界 if (marble.x < -marble.radius) { gameOver = true; } // 绘制大理石 ctx.beginPath(); ctx.arc(marble.x, marble.y, marble.radius, 0, Math.PI * 2); ctx.fillStyle = marble.color; ctx.fill(); }); drawScore(); // 每次渲染都检查得分,触发Promo if (score > 20) { drawPromo(); } requestAnimationFrame(animate); }
2. 完善drawGameOver的绘制参数
确保文本颜色、字体、位置都在画布可见范围内:
function drawGameOver() { // 先清屏,避免被之前的游戏元素覆盖 ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.fillStyle = '#ff0000'; ctx.font = '48px sans-serif'; ctx.textAlign = 'center'; ctx.fillText('游戏结束', canvas.width / 2, canvas.height / 2); ctx.font = '24px sans-serif'; ctx.fillText(`最终得分: ${score}`, canvas.width / 2, canvas.height / 2 + 50); }
3. 确保drawPromo的绘制逻辑正确
function drawPromo() { ctx.fillStyle = '#0066cc'; ctx.font = '20px sans-serif'; ctx.textAlign = 'left'; ctx.fillText('得分超过20啦!', 20, 30); }
关键注意点
- 游戏状态判断必须放在animate函数最开头,避免无效的游戏更新操作
- 所有绘制操作都要在
clearRect之后执行,防止被清屏覆盖 - 文本的
textAlign和绘制坐标要对应,确保文本显示在画布内
内容的提问来源于stack exchange,提问作者ipy11
相关产品推荐
相关产品推荐

