Search code examples
javascriptauto-update

The score is not updating. Can you please tell me what is wrong with the code?


The score is not updating. Please help me make the score update. When I click the button with the function for 'addScore', the displayed score will not change to a new one.

I have tried a lot of things. Non of which have worked


var score = 0;

function addScore(){ score ++ }

function drawScore() { 
 var c = document.getElementById("myCanvas");
 var ctx = c.getContext("2d");
 ctx.font = "16px Arial";
 ctx.fillStyle = "red";
 ctx.fillText("Score: " +score, 8, 20);
}

drawScore();

I am expecting it to update the score, but it does not. It remains at 0.

The problem has been solved bu the text keeps increasing and over laps it.


Solution

  • HTML elements are not reactive to variables changes. When you created the element with drawScore you informed the current score value and inserted this into DOM, however, updating score will not update this because it is not a reference.

    To make this work you will need to updated ctx text on every click. One simple example would be:

    
    var score = 0;
    var c = document.getElementById("myCanvas");
    var ctx = c.getContext("2d");
    
    function addScore(){
     score++;
     setScore();
    }
    
    function drawScore() { 
     ctx.font = "16px Arial";
     ctx.fillStyle = "red";
     setScore();
    }
    
    function setScore() {
     ctx.clearRect(0, 0, c.width, c.height);
     ctx.fillText("Score: " +score, 8, 20); 
    }
    
    drawScore();