Reputation: 65
Im trying to make a time line drawn on a HTML5 canvas with JavaScript. I started out with a while loop
, but it seems to malfunction within a requestAnimationFrame
function.
An if statement works fine, but Im wondering why the while loop and requestAnimationFrame function don't work together.
This code works
var x = 50
function animate(){
requestAnimationFrame(animate);
c.beginPath();
c.moveTo(50, halfway_y)
c.lineTo(x, halfway_y)
c.strokeStyle = "white"
c.lineWidth = 5;
c.stroke();
if(x < canvas.width - 50){
x+=7
}
}
animate()
This code doesn't work. The code just draws the line with no animation.
var x = 50
function animate(){
requestAnimationFrame(animate);
c.beginPath();
c.moveTo(50, halfway_y)
c.lineTo(x, halfway_y)
c.strokeStyle = "white"
c.lineWidth = 5;
c.stroke();
while(x < canvas.width){
x+=7
}
}
animate()
Upvotes: 1
Views: 230
Reputation: 4434
while(x < canvas.width) {
x+=7
}
if(x < canvas.width - 50) {
x+=7
}
The two code block is diffrent, while
blocks let x
to canvas.width
at once, if
blocks let x
to increase only 7
.
x = 0
while(x < canvas.width){
x+=7
}
console.log(x);// x = 999
x = 0
if(x < canvas.width - 50){
x+=7
}
console.log(x); // x = 7
Upvotes: 2