Bouncing Ball

by sirfizx

HTML

<body style="background-color:#e0e0e0">
    <h2>Canvas Ball Bounce</h2>
    <img id="ball" src="http://upload.wikimedia.org/wikipedia/commons/thumb/a/a8/Soccerball.png/55px-Soccerball.png" style="display:none" />
    <canvas id="can" height="400" width="600" style="position:relative;top:-50">
    </canvas>
</body>

JavaScript

var can, ctx, ball,
            x, y, xVec, yVec,
            direc, interval,
            rot = 0,
            gravity = 1,
            left = 55,
            right = 599,
            bottom = 325,
            centerOffset = -55;
 
        function init() {
            ball = document.getElementById("ball");
            can = document.getElementById("can");
            ctx = can.getContext("2d");
            ctx.strokeStyle = "black";
            // initialize position, speed, spin direction
            x = 98;
            y = 115;
            xVec = 5.5;
            yVec = 0;
            direc = 1;
            // draw lines for the ball to bounce off of
            ctx.moveTo(0, bottom );
            ctx.lineTo(600, bottom);
            ctx.lineTo(600, 0)
            ctx.stroke();
            // set animation to repeat every 40 ms
            interval = setInterval(animate, 40);
        }
 
        function animate() {
            model();
            // clear canvas except for lines at edge
            ctx.clearRect(0, 0, can.width - 1 , can.height - 1);
            draw();
        }
 
        function model() {
            
            x += xVec;
            yVec += gravity;
            y += yVec;
            bounceIf();
        }
 
        function bounceIf() {
            if (y >= bottom) {
                y = bottom;
                yVec = -1 * yVec - gravity;
                rot += .1 * direc;
            }
            if (x >= right || x <= left) {
                xVec *= -1;
                direc *= -1;
            }
        }
 
        function draw() {
            ctx.save();
            ctx.translate(x, y);
            //ctx.rotate(rot);
            ctx.drawImage(ball, centerOffset,centerOffset);
            ctx.restore();
        }
init();