¿Cómo construir una pelota que rebota con HTML y JavaScript?

La pelota que rebota se puede crear usando HTML, CSS y JavaScript y realizar algunas operaciones de rebote en esa pelota. Puede ver el artículo relacionado sobre cómo hacer una animación de rebote suave usando CSS.
Este artículo se dividirá en dos partes, la primera parte decidiremos el área donde la pelota que rebota realizará el rebote, básicamente, crearemos un lienzo donde se realizará el rebote. La segunda parte diseñará la pelota que rebota y le agregará algunas funciones de rebote.
Código HTML y CSS:El código HTML y CSS se utiliza para crear un área de lienzo donde rebotará la pelota. Usaremos una etiqueta de lienzo y usando JavaScript estructuraremos el círculo para la pelota dentro de ese lienzo. Y el CSS define el área del lienzo y el color de fondo del área del lienzo.
 

html

<!DOCTYPE HTML>
<html>
 
<head>
    <title>
        Bouncing Ball!!
    </title>
    <style>
        h1 {
            color: green;
        }
         
        canvas {
            background-color: #F08080;
            width: 600px;
            height: 400px;
            position: absolute;
            top: 20%;
            left: 20%;
        }
    </style>
</head>
 
<body>
    <center>
        <h1>GeeksforGeeks</h1>
        <h3>Bouncing ball using JavaScript</h3>
        <canvas>
        </canvas>
    </center>
</body>
 
</html>

Código JavaScript: es la parte central de este artículo donde estructuraremos la pelota y realizaremos la tarea de botar. Asignaremos 4 variables, 2 para las coordenadas del círculo (pelota) creado y otras dos para la velocidad respectiva de la pelota que rebota. La variable radio se usa para el radio de la bola. También necesitamos despejar el área del lienzo para hacerlo, usaremos la función clearReact() . Todo el rebote y la coordinación se decidirán mediante la función math.random() .
 

javascript

<script>
    var canvas = document.querySelector("canvas");
 
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;
 
    var l = canvas.getContext('2d');
 
    // x and y are the coordinates of the circle
    // vx and vy are the respective speeds
    var x = Math.floor(Math.random() * innerWidth);
    var y = Math.floor(Math.random() * innerHeight);
    var vx = Math.floor(Math.random() * 2);
    var vy = Math.floor(Math.random() * 4);
    var radius = 20;
 
    move();
   
    // This function will do the animation
    function move() {
        requestAnimationFrame(move);
 
        // It clears the specified pixels within
        // the given rectangle
        l.clearRect(0, 0, innerWidth, innerHeight);
 
        // Creating a circle
        l.beginPath();
        l.strokeStyle = "black";
        l.arc(x, y, radius, 0, Math.PI * 2, false);
        l.stroke();
 
        // Conditions so that the ball bounces
        // from the edges
        if (radius + x > innerWidth)
            vx = 0 - vx;
 
        if (x - radius < 0)
            vx = 0 - vx;
 
        if (y + radius > innerHeight)
            vy = 0 - vy;
 
        if (y - radius < 0)
            vy = 0 - vy;
 
        x = x + vx;
        y = y + vy;
 
    }
</script>

Código completo: Es la combinación de las dos secciones anteriores, es decir, combinar código HTML, CSS y JavaScript. Este código creará una salida donde un diseño vall rebotará en un patrón aleatorio.
 

html

<!DOCTYPE HTML>
<html>
 
<head>
    <title>
        Bouncing Ball!!
    </title>
    <style>
        h1 {
            color: green;
        }
         
        canvas {
            background-color: #F08080;
            width: 600px;
            height: 400px;
            position: absolute;
            top: 20%;
            left: 20%;
        }
    </style>
 
</head>
 
<body>
    <center>
        <h1>GeeksforGeeks</h1>
        <h3>Bouncing ball using JavaScript</h3>
        <canvas>
        </canvas>
        <script>
            var canvas = document.querySelector("canvas");
 
            canvas.width = window.innerWidth;
            canvas.height = window.innerHeight;
 
            var l = canvas.getContext('2d');
 
            // x and y are the co-ordinates of the circle
 
            // vx and vy are the respective speeds
 
            var x = Math.floor(Math.random() * innerWidth);
            var y = Math.floor(Math.random() * innerHeight);
            var vx = Math.floor(Math.random() * 2);
            var vy = Math.floor(Math.random() * 4);
            var radius = 20;
 
            move();
           
            // This function will do the animation
            function move() {
                requestAnimationFrame(move);
 
                // It clears the specified pixels within
                // the given rectangle
                l.clearRect(0, 0, innerWidth, innerHeight);
 
                // Creating a circle
                l.beginPath();
                l.strokeStyle = "black";
                l.arc(x, y, radius, 0, Math.PI * 2, false);
                l.stroke();
 
                // Conditions sso that the ball bounces
                // from the edges
                if (radius + x > innerWidth)
                    vx = 0 - vx;
 
                if (x - radius < 0)
                    vx = 0 - vx;
 
                if (y + radius > innerHeight)
                    vy = 0 - vy;
 
                if (y - radius < 0)
                    vy = 0 - vy;
 
                x = x + vx;
                y = y + vy;
 
            }
        </script>
    </center>
</body>
 
</html>

Producción: 
 

Publicación traducida automáticamente

Artículo escrito por lakshita y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *