Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
125
rated 0 times [  131] [ 6]  / answers: 1 / hits: 15923  / 8 Years ago, sat, november 12, 2016, 12:00:00

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.


More From » html

 Answers
32

If I understand you correctly, you only want to redraw on the button click, i.e. on a radius change. You don't need any timing functions for this, you can call the draw function whenever a radius change happens:



//Define globals
var radiusIncrement = 5;
var ballRadius = 20;
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');

//initialize
draw();

//Helper functions
function increaseRadius() {
ballRadius += radiusIncrement;
draw();
}

function decreaseRadius() {
if (ballRadius > 0) {
ballRadius -= radiusIncrement;
draw();
}
}


//Draw handler
function draw() {
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.beginPath();
ctx.arc(canvas.height/2,canvas.width/2,ballRadius,0,2*Math.PI);
ctx.stroke();
}


As you can see I also extracted the variable definition for canvas and ctx out of the draw function, since you don't need to re-assign these on every draw call.


[#60084] Thursday, November 10, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
gilbertomaximilianod

Total Points: 208
Total Questions: 96
Total Answers: 111

Location: Northern Mariana Islands
Member since Wed, Feb 24, 2021
3 Years ago
;