I'm trying to increase the radius of a circle drawn in canvas using JavaScript functions.
There were many topics with similar issues but couldn't find an answer that would fix this one, I've tried using built-in methods that were suggested like setInterval
, setTimeout
, window.requestAnimationFrame
and clearing the canvas to redraw the circle with the updated variable.
So far the setInterval
method displayed the update but kept the previous iterations in the canvas, the clear method doesn't work.
Here's the example :
//Define globals
var radiusIncrement = 5;
var ballRadius = 20;
//Helper functions
function increaseRadius() {
ballRadius += radiusIncrement;
}
function decreaseRadius() {
if (ballRadius > 0) {
ballRadius -= radiusIncrement;
}
}
//Draw handler
function draw() {
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
ctx.beginPath();
ctx.arc(canvas.height/2,canvas.width/2,ballRadius,0,2*Math.PI);
ctx.stroke();
}
//Event handler
setInterval(function() {
draw();
ctx.clearRect(0,0,canvas.width,canvas.height);
}, 100);
<!--Create frame and assign callbacks to event handlers-->
<button type=button onclick=increaseRadius()>Increase Radius</button>
<button type=button onclick=decreaseRadius()>Decrease Radius</button>
<canvas id=myCanvas width=400 height=400 style=border:1px solid #000000;></canvas>
Rather than using setInterval, is there a way to streamline the code using and use an event handler to refresh the canvas on every onlick ?
Thanks for your help.
Cheers.