I just joined this platform and I'm trying to create an animation using canvas. My goal is to redraw a circle every 2 seconds with a canvas reset in between. The circle should appear randomly within the canvas, which I was able to accomplish. However, I'm struggling to make the animation repeat itself every 2 seconds. I tried using the requestAnimationFrame callback, but it refreshes too quickly, around 60 times per second.
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var requestAnimationFrame = window.requestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.msRequestAnimationFrame;
function reset(){
draw();
requestAnimationFrame(reset);
}
function draw(){
var X = Math.floor(Math.random()*canvas.width);
var Y = Math.floor(Math.random()*canvas.height);
var radius = 70;
context.clearRect(0,0, canvas.width, canvas.height);
context.beginPath();
context.arc(X, Y, radius, 0, 2 * Math.PI, false);
context.fillStyle = 'red';
context.fill();
}
function main(){
requestAnimationFrame(reset);
}
main();
I followed your advice and updated the code, now I see circles every two seconds, but the canvas is not resetting in between.
function main(){
setInterval(function(){
draw();
context.clearRect(0,0, 640,480);
},2000);
};
I believe I found a solution, or at least a way to approach it. I combined your suggestion with a setTimeout function.
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
function draw() {
var X = Math.floor(Math.random() * canvas.width);
var Y = Math.floor(Math.random() * canvas.height);
var radius = 70;
context.beginPath();
context.arc(X, Y, radius, 0, 2 * Math.PI, false);
context.fillStyle = 'red';
context.fill();
}
function reset() {
canvas.width = canvas.width;
}
function action() {
draw();
setTimeout(function() {
reset()
}, 2000);
}
function main() {
setInterval(function() {
action();
}, 2200);
}
main();