JSFiddle - React, Tailwind, and code Playground

by wookiehangover

CSS

body {background-color:#fff; margin:4em;padding:0;}

JavaScript

if (!window.requestAnimationFrame) {
    window.requestAnimationFrame = (window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function (callback) {
        return window.setTimeout(callback, 1000/60); });
}

function Ticker() {
  this._ticks = 0;
}

Ticker.prototype.tick = function() {
  this._ticks++;
}

Ticker.prototype.getTicks = function() {
  return this._ticks;
}

function SpriteAnimation(spritesheet, frames, speed, scale) {
  this.scale = scale;
  this.spritesheet = spritesheet
  this.frames = frames;
  this.xpos = 0;
  this.ypos = 0;
  this.index = 0;
  this.speed = speed;
}

SpriteAnimation.prototype.getFrameSize = function() {
  return this.spritesheet.frameSize;
}

SpriteAnimation.prototype.draw = function(context, ticker) {
  context.drawImage(this.spritesheet.spriteImage,
                    this.xpos,
                    this.ypos,
                    this.getFrameSize(),
                    this.getFrameSize(),
                    0,
                    0,
                    this.getFrameSize() * this.scale,
                    this.getFrameSize() * this.scale
                   );
  this.spritesheet.frameAtIndex(this.index).xpos;
  if (ticker.getTicks() % this.speed == 0) {

    this.index += 1;
    pos = this.spritesheet.frameAtIndex(this.index % this.frames.length);
    this.setPosition(pos);
  }
}

SpriteAnimation.prototype.setPosition = function(frameAtIndex) {
    this.xpos = this.getFrameSize() * frameAtIndex.xpos;
    this.ypos = this.getFrameSize() * frameAtIndex.ypos;
}

function SpriteSheet(source, frameSize, scale) {
  this.scale = scale || 1;
  this.frameSize = frameSize;
  this.spriteImage = new Image();
  this.spriteImage.src = source;
  this.ready = false;
  $this = this

  this.spriteImage.onload = function() {
    $this.ready = true
  }
}

SpriteSheet.prototype.createAnimation = function(frames) {
  return new SpriteAnimation(this, frames, 1,...