JSFiddle - React, Tailwind, and code Playground

by Anderson Carlos Woss

HTML

<div id="character"></div>

CSS

body {
  background: white;
}

#character {
  position: fixed;
  width: 36px;
  height: 50px;
  background: url(https://i.imgur.com/oz5I0Af.png) -2px -5px no-repeat;
}

#character[data-direction="right"] {
  background-position: -40px -180px;
}

#character[data-direction="left"] {
  background-position: -2px -120px;
}

#character[data-direction="up"] {
  background-position: -2px -60px;
}

#character[data-direction="down"] {
  background-position: -2px -5px;
}

JavaScript

const DIRECTIONS = {
  LEFT: 37,
  RIGHT: 39,
  UP: 38,
  DOWN: 40
}

class Character {
	
  

  constructor(id) {
    this.direction = "down"
    this.left = 0
    this.top = 0
    this.element = document.getElementById(id)
    this.animation = ["-2px", "-40px", "-70px", "-115px"]
    this.counter = 0
  }
  
  move(direction) {
    switch (direction) {
      case DIRECTIONS.LEFT:
        this.element.dataset.direction = "left"
        this.left -= 10;
        break
      case DIRECTIONS.RIGHT:
        this.element.dataset.direction = "right"
        this.left += 10;
        break
      case DIRECTIONS.UP:
        this.element.dataset.direction = "up"
        this.top -= 10;
        break
      case DIRECTIONS.DOWN:
        this.element.dataset.direction = "down"
        this.top += 10;
        break
    }
    
    this.element.style.left = `${this.left}px`
    this.element.style.top = `${this.top}px`
    this.element.style.backgroundPositionX = this.animation[this.counter++ % 4]
  }
}

const character = new Character("character")

document.addEventListener("keydown", function(event) {
  character.move(event.keyCode)
})