LoneCoder
LoneCoder

Reputation: 40

Bouncing balls drawing inside a canvas, javascript

function refBalls(){
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var circles = [{x:40,y:100,r:20,color:'black',vx:5,vy:10}]
function draw(){
    ctx.beginPath();
    ctx.arc(circles[0].x, circles[0].y, circles[0].r, 0, 2 * Math.PI);
    ctx.fillStyle = "blue";
    ctx.fill();
    if( (circles[0].x + circles[0].r + circles[0].vx > c.width + c.style.left) || (circles[0].x - circles[0].r + circles[0].vx < c.style.left) ){
        circles[0].vx = -circles[0].vx;
    }
    circles[0].x += circles[0].vx;
    requestAnimationFrame(draw);
}
requestAnimationFrame(draw);}

I am able to see the ball moving but I'm seeing its previous position. I should be seeing a ball moving, instead I'm seeing a strip like a ball painting on the canvas. Can someone help me? this is what I'm seeing in my browser

Upvotes: 0

Views: 186

Answers (1)

dcbarans
dcbarans

Reputation: 493

You will need to clear your canvas every time you draw the frame. This is the same way video games render their content onto the screen.

Some examples here: How to clear the canvas for redrawing

Upvotes: 1

Related Questions