HTML5 Game - Bouncing ball drag and drop

Description

Bouncing ball drag and drop

Demo

ResultView the demo in separate window

<!doctype html>
<html>

<body>
    <canvas id="canvas" width="700" height="500"></canvas>
    <script>
        class Ball {/*from  w w  w. j av  a2  s.  co  m*/
            constructor(radius, color) {
                this.radius = radius;
                this.color = color;
                this.x = 0;
                this.y = 0;
                this.vx = 0;
                this.vy = 0;
            }
            draw(context) {
                context.fillStyle = this.color;
                context.beginPath();
                context.arc(this.x, this.y, this.radius, 0, 2 * Math.PI, true);
                context.closePath();
                context.fill();
            }

        }

        let canvas = document.getElementById('canvas');
        let context = canvas.getContext('2d');

        let g = 0.1;
        let radius = 20;
        let color = "#0000ff";
        let ball;
        let isDragging = false;

        window.onload = init;

        function init() {
            ball = new Ball(radius, color);
            ball.x = 50;
            ball.y = canvas.height - radius;
            ball.vx = 0;
            ball.vy = 0;
            ball.draw(context);

            canvas.addEventListener('mousedown', function() {
                canvas.addEventListener('mousemove', onDrag, false);
                canvas.addEventListener('mouseup', onDrop, false);
            }, false);
            setInterval(onEachStep, 1000 / 60);
        };

        function onDrag(evt) {
            isDragging = true;
            ball.x = evt.clientX;
            ball.y = evt.clientY;
        }

        function onDrop() {
            isDragging = false;
            canvas.removeEventListener('mousemove', onDrag, false);
            canvas.removeEventListener('mouseup', onDrop, false);
        }

        function onEachStep() {
            if (isDragging == false) {
                ball.vy += g;
                ball.x += ball.vx;
                ball.y += ball.vy;

                if (ball.y > canvas.height - radius) {
                    ball.y = canvas.height - radius;
                    ball.vy *= -0.8;
                }
                if (ball.x > canvas.width + radius) {
                    ball.x = -radius;
                }
            }
            context.clearRect(0, 0, canvas.width, canvas.height);
            ball.draw(context);
        };
    </script>
</body>

</html>

Related Topic