V
Vinicius Carvalho
Hi there! I'm starting with canvas, and I'm trying a simple example of
animation by moving a circle from x0,y0 to x1,y1.
My first attempt:
var canvas;
var ctx;
var x=100,y=100;
var interval;
function draw(){
canvas = document.getElementById("canvas");
if(canvas.getContext){
ctx = canvas.getContext("2d");
}
}
function animate(){
x++;
y++;
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.fillStyle = "#f00";
ctx.arc(x,y,20,0,2*Math.PI,false);
ctx.fill();
if(x>400){
clearInterval(interval);
}
}
function start(){
interval = setInterval("animate()",20);
}
That makes the ball move, but it does not clear the canvas. I was
debugging and on the clearRect command it does clear the canvas, but
when painting it again, the old circles are still there.
I tried to solve by using save() and restore() and it did not work.
For some reason, beginPath() and endPath() do solve the issue. I'm
just wondering why would I need it? Why can't I just use save and
restore?
Regards
animation by moving a circle from x0,y0 to x1,y1.
My first attempt:
var canvas;
var ctx;
var x=100,y=100;
var interval;
function draw(){
canvas = document.getElementById("canvas");
if(canvas.getContext){
ctx = canvas.getContext("2d");
}
}
function animate(){
x++;
y++;
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.fillStyle = "#f00";
ctx.arc(x,y,20,0,2*Math.PI,false);
ctx.fill();
if(x>400){
clearInterval(interval);
}
}
function start(){
interval = setInterval("animate()",20);
}
That makes the ball move, but it does not clear the canvas. I was
debugging and on the clearRect command it does clear the canvas, but
when painting it again, the old circles are still there.
I tried to solve by using save() and restore() and it did not work.
For some reason, beginPath() and endPath() do solve the issue. I'm
just wondering why would I need it? Why can't I just use save and
restore?
Regards