Game

mail@pastecode.io avatar
unknown
javascript
a month ago
1.2 kB
0
Indexable
Never
// Create a canvas element
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
canvas.width = 640;
canvas.height = 480;
document.body.appendChild(canvas);

// Load the football image
const ballImg = new Image();
ballImg.src = 'https://i.imgur.com/5J9Xz8P.png';

// Set the initial position of the ball
let ballX = canvas.width / 2 - ballImg.width / 2;
let ballY = canvas.height / 2 - ballImg.height / 2;

// Set the speed of the ball
let ballSpeedX = 5;
let ballSpeedY = 5;

// Draw the ball on the canvas
function drawBall() {
  ctx.drawImage(ballImg, ballX, ballY);
}

// Update the position of the ball
function updateBall() {
  ballX += ballSpeedX;
  ballY += ballSpeedY;

  // Bounce the ball off the walls
  if (ballX + ballImg.width > canvas.width || ballX < 0) {
    ballSpeedX = -ballSpeedX;
  }
  if (ballY + ballImg.height > canvas.height || ballY < 0) {
    ballSpeedY = -ballSpeedY;
  }
}

// Clear the canvas and redraw the ball
function draw() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  drawBall();
}

// Update the ball position and redraw the canvas
function update() {
  updateBall();
  draw();
}

// Start the game loop
setInterval(update, 30);
Leave a Comment