JSFiddle - React, Tailwind, and code Playground
JavaScript
(function () {
// create a game sprite, then update and draw it on a continuous loop
'use strict';
var canvas, context, Sprite, sprite, gameLoop;
// create the canvas and context for drawing
canvas = document.createElement('canvas');
context = canvas.getContext('2d');
document.body.appendChild(canvas);
// sprite constructor
Sprite = function () {
// the sprite's walking animation, consisting of three frames
// (just using filled rectangles for simplicity here)
this.walkingFrames = ['#111111', '#222222', '#333333'];
this.walkingFramesIndex = 0;
// sprite's x position, y position, width, and height on the canvas
this.x = 0;
this.y = 0;
this.w = 100;
this.h = 100;
// an array of functions that the sprite will execute on every game loop
this.actions = [this.animate];
// placeholder for troubleshooting purposes
this.holder = 'whatever';
};
// sprite methods
Sprite.prototype = {
// execute the functions in the sprite's action array
update: function () {
// ~~~~~~~ BREAKS THE SCRIPT IF UNCOMMENTED ~~~~~~~
// this.actions[0]();
// ~~~~~~~~~~ WORKS FINE ~~~~~~~~~~
this.holder = this.actions[0];
this.holder();
},
// draw the sprite's current walking frame
// (again, just using filled rectangles for simplicity's sake)
draw: function () {
context.fillStyle = this.walkingFrames[this.walkingFramesIndex];
context.fillRect(this.x, this.y, this.w, this.h);
},
// increment the sprite's current walking frame (or reset it to 0)
animate: function () {
if (this.walkingFramesIndex <= this.walkingFrames.length - 1) {
this.walkingFramesIndex += 1;
} else {
this.walkingFramesIndex = 0;
}
}
};
// create a new sprite
sprite = new Sprite();
// update and draw the sprite on a continuous loop
gameLoop = function () {
window.requestAnimationFrame(gameLoop);
sprite.update();
sprite.draw();
};
// start the game loop
window.requestAnimationFrame(gameLoop);
}());