Search code examples
javascripthtmlhtml5-canvasreplit

Text displaying twice in different fonts | Javascript Canvas


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)


Solution

  • 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