HTML5 Game - Bouncing ball with random starting point

Description

Bouncing ball with random starting point

Demo

ResultView the demo in separate window

<!doctype html>
<html>

<head>

<body>
    <canvas id="canvas" width="700" height="500"></canvas>
    <script>
        let canvas = document.getElementById('canvas');
        let context = canvas.getContext('2d');

        let radius = 20;//from   w  w w .  ja  v  a2  s. co m
        let color = "red";
        let g = 0.1; // gravity acceleration 
        let x = 50; // starting X position
        let y = 50; // starting Y position
        let vx = Math.random() * 5; // starting horizontal speed
        let vy = (Math.random() - 0.5) * 4; // starting vertical speed

        window.onload = init;

        function init() {
            setInterval(onEachStep, 1000 / 60); // 60 fps
        };

        function onEachStep() {
            vy += g; // gravity increases the vertical speed
            x += vx; // horizontal speed increases horizontal position 
            y += vy; // vertical speed increases vertical position

            if (y > canvas.height - radius) { // if ball hits the ground
                y = canvas.height - radius; // reposition it at the ground
                vy *= -0.8; // reverse and reduce its vertical speed
            }
            if (x > canvas.width + radius) { // if ball goes beyond canvas
                x = -radius; // wrap it around 
            }
            // draw the ball
            context.clearRect(0, 0, canvas.width, canvas.height);
            context.fillStyle = color;
            context.beginPath();
            context.arc(x, y, radius, 0, 2 * Math.PI, true);
            context.closePath();
            context.fill();

        };
    </script>
</body>

</html>

Related Topic