1

I am creating a game using javascript on repl.it. I have run into a problem with the menu screen of my game. The title text for my game displays twice in different fonts over eachother. However, if I refresh the window, the text displays normally. What's causing this and how can I fix it? Thank you.

The game: Game
My code: Code

picture of bug

(picture of bug)

Joyal Mathew
  • 614
  • 7
  • 24

1 Answers1

2

You need to run ctx.clearRect(0, 0, width, height) before rendering your text in your menu function to clear the previously drawn text before redrawing it again.

function menu() {
    ctx.clearRect(0, 0, width, height);
    ctx.font = "75px Oswald";
    ctx.textAlign = "center";
    ctx.fillStyle = txtColor;
    ctx.fillText("Almost Pong!", 250, 200);
    ctx.font = "25px Oswald";
    ctx.fillText("space for two player", 250, 250);
    ctx.fillText("c for one player", 250, 300);
    if (start) {
      addEventListener('keydown', keyDown2, false); addEventListener('keyup', keyUp2, false);
      start = false;
      clearInterval(me_nu);
      anim = setInterval(game, 10);
    }
    if (compStart) {
      p1.name = "CPU";
      compStart = false;
      clearInterval(me_nu);
      anim = setInterval(game, 10);
      compute = true;
    }
 }

Fixed Code: https://repl.it/repls/MediumpurpleNearMalware

Result: https://mediumpurplenearmalware--five-nine.repl.co

  • Thanks! Why was the text displaying in a different font in the first place? I defined the font before filling it. – Joyal Mathew Oct 31 '18 at 01:18
  • 1
    It takes a bit of time for the font to load, so it probably renders in the default browser font before it loads your font and starts drawing it. – Sensational Code Oct 31 '18 at 01:22