Sean W
Sean W

Reputation: 323

How to make a counter using a canvas in javascript

I'm trying to make a counter so that every time you click your mouse it shows the number of clicks in the canvas. But it isn't updating the canvas.

<!DOCTYPE html>
<html>
<body>

<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>


<button onclick="function1()">Click Here</button>

<script>
var animate = setInterval(window.requestAnimationFrame,1)

var clicks = 0;
        function function1()
        {
        clicks++;
        document.getElementById('myCanvas').innerHTML = clicks;
        }; 
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.font="16px Verdana";
ctx.fillText("Score: " + clicks,190,20);
</script>
</body>
</html>

Upvotes: 0

Views: 2850

Answers (2)

Robin
Robin

Reputation: 7895

So I changed the code to add a redraw() function to redraw on the canvas the new number.

And the increment() function will call that one after doing clicks++.

var clicks = 0;
function increment(){
    clicks++;
    redraw();
};
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
console.log(ctx);
function redraw(){
    ctx.clearRect(0, 0, c.width, c.height);
    ctx.font="16px Verdana";
    ctx.fillText("Score: " + clicks,190,20);
}
redraw();

You can't just use innerHTML for canvas because it is really just a surface for drawing on thus it is not affected by it's inner DOM.

Here is a working JSFiddle demo.

Upvotes: 1

juvian
juvian

Reputation: 16068

Your code throws an error, window.requestAnimaitonFrame requires a callback to a function as parameter. This code works:

var animate = setInterval(function(){update()},1)

var clicks = 0;
    function function1()
    {
    clicks++;
    }; 
function update(){

    var c=document.getElementById("myCanvas");
    var ctx=c.getContext("2d");
    ctx.clearRect(0,0,c.width,c.height);
    ctx.font="16px Verdana";
    ctx.fillText("Score: " + clicks,190,20);
}

Upvotes: 0

Related Questions