make a ball bounce in javascript

One way to make a ball bounce in Javascript is by using the HTML5 canvas element along with basic physics and animation principles. Here's some sample code to create a bouncing ball animation:

<!DOCTYPE html>
<html>
<head>
  <title>Bouncing Ball</title>
  <style>
    canvas {
      border: 1px solid black;
    }
  </style>
</head>

<body onload="setup()">
  <canvas id="myCanvas"></canvas>
  
  <script>
    var canvas = document.getElementById('myCanvas');
    var ctx = canvas.getContext('2d');
    var x = canvas.width/2;
    var y = canvas.height-30;
    var dx = 3;
    var dy = -3;
    var ballRadius = 10;

    function drawBall() {
      ctx.beginPath();
      ctx.arc(x, y, ballRadius, 0, Math.PI*2);
      ctx.fillStyle = "#0095DD";
      ctx.fill();
      ctx.closePath();
    }

    function draw() {
      ctx.clearRect(0, 0, canvas.width, canvas.height);
      drawBall();

      // Bouncing logic
      if(x + dx > canvas.width-ballRadius || x + dx < ballRadius) {
        dx = -dx;
      }
      if(y + dy > canvas.height-ballRadius || y + dy < ballRadius) {
        dy = -dy;
      }
      x += dx;
      y += dy;
    }

    function setup() {
      setInterval(draw, 10);
    }
  </script>
</body>
</html>
1033 chars
53 lines

This script will create a canvas element and draw a circle at the center that will move and simulate a bouncing ball. The draw() function is called repeatedly with a small delay (10ms), which simulates the animation. The drawBall() function creates a ball at current location with a color fill. Finally, the if statements will detect if the ball is hitting any of the canvas' boundaries and change the direction accordingly to simulate a bouncing motion.

gistlibby LogSnag