JSFiddle - React, Tailwind, and code Playground

Canvas with moving ball

by Varayut Lerdkanlayanawat

HTML

<canvas id="myCanvas" width="300" height="200" style="border:1px solid #000000;"></canvas>

JavaScript

// Create a canvas
const canvas = document.getElementById('myCanvas');

// Create a ball
const ctx = canvas.getContext("2d");
const horizontalVelocity = 20;
const verticalVelocity = 10;
let x = 0;
let y = 0;
ctx.fillRect(x, y, 20, 20);

// Check a condition
let horizontalDirection = 'right';
let verticalDirection = 'up';

function checkDirection(x, y) {
  if (x >= canvas.width - 20) {
    horizontalDirection = 'left';
  } else if (x <= 0) {
    horizontalDirection = 'right';
  }

  if (y >= canvas.height - 20) {
    verticalDirection = 'up';
  } else if (y <= 0) {
    verticalDirection = 'down';
  }
}

function clearCanvas() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
}

// Move the ball by using interval
setInterval(() => {
  clearCanvas();
  checkDirection(x, y);

  if (horizontalDirection === 'right') {
    x += horizontalVelocity;
  } else {
    x -= horizontalVelocity;
  }

  if (verticalDirection === 'down') {
    y += verticalVelocity;
  } else {
    y -= verticalVelocity;
  }

  ctx.fillRect(x, y, 20, 20);
}, 100);