JSFiddle - React, Tailwind, and code Playground

by extempl

HTML

<canvas id="canvas" ></canvas>

JavaScript

let canvasWidth = 400;
let canvasHeight = 550;
let spriteWidth = 500;
let spriteHeight = 250;
let rows = 1;
let cols = 2;
let width = spriteWidth / cols;
let height = spriteHeight / rows;
let curFrame = 0;
let frameCount = 2;
let x = 0;
let y = -100;
let srcX;
let srcY;
let right = true;
let speed = -12;
let canvas = document.getElementById("canvas");
canvas.width = canvasWidth;
canvas.height = canvasHeight;

let ctx = canvas.getContext("2d");

let character = new Image();
 character.onload = function () {
   setInterval(draw, 500);
 }

character.src = "https://freeiconshop.com/wp-content/uploads/edd/bulb-curvy-flat.png";
function updateFrame() {
  curFrame = ++curFrame % frameCount;
  srcX = curFrame * width;
  ctx.clearRect(x, y, width, height);

  srcY = 0 * height;
  y -= speed;
}

function draw() {
  updateFrame();
  ctx.drawImage(character, srcX, srcY, width, height, x, y, width, height);
}

//setInterval(draw, 500);