create an animation of a boy throwing a baseball in javascript

To create an animation of a boy throwing a baseball in Javascript, we can use the HTML5 Canvas element to draw each frame of the animation. The canvas allows us to manipulate pixels and render graphics which can be used to create animations. Here are the steps to create the animation:

  1. Create a canvas element in your HTML file:
<canvas id="canvas" width="500" height="400"></canvas>
55 chars
2 lines
  1. Get the canvas context and set up the initial variables:
index.tsx
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');

let x = 0;
let y = canvas.height - 50;
let dx = 5;
let dy = -5;
let angle = 0;
let thrown = false;
187 chars
10 lines
  1. Draw the boy and the baseball:
index.tsx
function drawBoy() {
  ctx.beginPath();
  ctx.fillStyle = '#000000';
  ctx.arc(x, y, 10, 0, Math.PI * 2);
  ctx.fill();
  ctx.moveTo(x, y + 10);
  ctx.lineTo(x, y + 30);
  ctx.strokeStyle = '#000000';
  ctx.stroke();
}

function drawBaseball() {
  ctx.beginPath();
  ctx.fillStyle = '#FFFFFF';
  ctx.arc(x, y, 5, 0, Math.PI * 2);
  ctx.fill();
}
346 chars
18 lines
  1. Create an animation loop that updates the position of the ball and animates the throwing motion:
index.tsx
function animate() {
  // Clear the canvas
  ctx.clearRect(0, 0, canvas.width, canvas.height);

  // Draw the boy and the baseball
  drawBoy();
  drawBaseball();

  // Update the position of the ball
  if (x > canvas.width - 10 || x < 10) {
    dx = -dx;
  }
  x += dx;
  y += dy;

  // Animate the throwing motion
  if (!thrown) {
    if (angle < 90) {
      angle += 1;
      dy -= 1;
    } else {
      thrown = true;
    }
  }

  requestAnimationFrame(animate);
}
468 chars
28 lines
  1. Call the animate function to start the animation:
index.tsx
animate();
11 chars
2 lines

This will create an animation of a boy throwing a baseball on an HTML canvas.

gistlibby LogSnag