问题
I'm new here and trying to get canvas to work for me. I wanted to make a canvasanimation where a circle was redrawn every 2 seconds with a canvas reset in between. The circle should appear randomly within(which i managed to get to work) but i cant figure out how to get the animation to repeat itself every 2 seconds. I used the requestAnimationFrame callback, but this refreshes like 60 times a 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 updated the code like you said, but now i get 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 think I found it, or at least a way to do it. I combined your answer 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();
回答1:
You can use the timestamp that requestAnimationFrame
feeds to its animation function to throttle the drawing to 1 frame-per-second.
Given the timestamp fed into your animation loop, calculate the milliseconds that have elapsed since the last draw. If 1000ms haven't elapsed, do nothing. If 1000ms have elapsed, do the draw() and reset the startTime to wait for another 1000ms to elapse.
Example code and a Demo: http://jsfiddle.net/m1erickson/mwuc0tby/
var startTime;
var interval=1000;
requestAnimationFrame(animate);
function animate(t){
requestAnimationFrame(animate);
if(!startTime){startTime=t;}
if(t-startTime<interval){return;}
startTime=t;
draw();
}
I suggest using requestAnimationFrame because it comes with some nice built-in efficiencies in terms of resources and performance.
回答2:
You can use setInterval
instead:
setInterval(function() {
// draw the circle
// reset
}, 2000);
来源:https://stackoverflow.com/questions/25222729/drawing-a-shape-in-canvas-on-repeat