HTML5 Game - Pause bounding ball after mouse down

Description

Pause bounding ball after mouse down

Demo

ResultView the demo in separate window

<!doctype html>
<html>

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

        let radius = 20;//ww  w .  j a  va 2  s . c o m
        let color = "#0000ff";
        let g = 0.1; // gravity acceleration 
        let x = 50; // starting X position
        let y = 50; // starting Y position
        let vx = 2; // starting horizontal speed
        let vy = 0; // starting vertical speed

        window.onload = init;

        function init() {
            canvas.addEventListener('mousedown', stopAnim, false);
            canvas.addEventListener('mouseup', startAnim, false);
            startAnim();
        };

        function startAnim() {
            interval = setInterval(onEachStep, 1000 / 60); // 60 fps
        }

        function stopAnim() {
            clearInterval(interval);
        }

        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