JSFiddle - React, Tailwind, and code Playground

by Chris

CoffeeScript

// Get a reference to the canvas element.
const canvas = document.getElementById('myCanvas');

// Get the canvas context.
const ctx = canvas.getContext('2d');

// Create a ball object.
const ball = {
  x: 100,
  y: 100,
  radius: 10,
  vx: 0,
  vy: 0,
  gravity: 9.81,
};

// Draw the ball on the canvas.
function drawBall() {
  ctx.fillStyle = 'red';
  ctx.fillRect(ball.x - ball.radius, ball.y - ball.radius, ball.radius * 2, ball.radius * 2);
}

// Update the position of the ball.
function updateBall() {
  ball.vy += ball.gravity;
  ball.y += ball.vy;

  if (ball.y + ball.radius >= canvas.height) {
    ball.y = canvas.height - ball.radius;
    ball.vy = -ball.vy;
  }
}

// Animate the ball.
function animate() {
  updateBall();
  drawBall();

  requestAnimationFrame(animate);
}
console.log(animate());