var fps = 4;
var head = 0;
var fpsEl = document.getElementById("fps");
var debugEl = document.getElementById("debug");
var marioEl = document.getElementById("mario");
var anims = {
hammerWL: [0, 2, 1, 3], // walk left
hammerWR: [7, 5, 6, 4] // walk right
};
var anim = [].concat(
anims.hammerWL, // L
anims.hammerWL, // L
anims.hammerWR, // R
anims.hammerWL, // L
anims.hammerWR // R
);
fpsEl.value = fps;
fpsEl.onclick = updateFps;
fpsEl.onkeyup = updateFps;
fpsEl.onchange = updateFps;
debug.onclick = toggleDebug;
debug.onchange = toggleDebug;
function updateFps () {
fps = parseInt(this.value, 10) || 0;
}
function updateFrame (frame) {
marioEl.setAttribute("class", frame);
}
function toggleDebug () {
var c = this.checked ? "debug" : "";
document.body.setAttribute("class", c);
}
// !function loop () { ... }();
// is a shortcut for
// loop(); function loop () { ... }
// declared and called at the same time
!function loop () {
if (fps === 0) {
setTimeout(loop, fps);
} else {
// head = 0, 1, 2, ..., 0, ...
head = (head + 1) % anim.length;
updateFrame("frame_" + anim[head]);
setTimeout(loop, 1000 / fps);
}
}();
html {
height: 100%;
}
body {
margin: 0;
height: 100%;
background: black;
}
#controls {
background: #ddd;
line-height: 40px;
padding: 0 .5em;
height: 40px;
}
#fps {
width: 50px;
}
#stage {
position: relative;
background: yellow;
border: 10px solid black;
height: calc(100% - 60px);
width: calc(100% - 20px);
}
/* sprite */
#mario {
position: absolute;
left: 50%;
bottom: 0;
height: 0;
width: 0;
}
#mario img {
display: block;
position: absolute;
background: url(https://i.sstatic.net/yScim.png);
}
.debug #mario img {
background-color: #0090ff;
}
/* frames / hammer walk left */
#mario.frame_0 img {
background-position: -4px -10px;
width: 26px; height: 58px;
left: -13px; bottom: 0;
}
#mario.frame_1 img {
background-position: -70px -24px;
width: 52px; height: 32px;
left: -37px; bottom: 0;
}
#mario.frame_2 img {
background-position: -162px -10px;
width: 30px; height: 58px;
left: -15px; bottom: 0;
}
#mario.frame_3 img {
background-position: -232px -24px;
width: 50px; height: 32px;
left: -37px; bottom: 0;
}
/* frames / hammer walk right */
#mario.frame_4 img {
background-position: -310px -24px;
width: 50px; height: 32px;
right: -37px; bottom: 0;
}
#mario.frame_5 img {
background-position: -400px -10px;
width: 30px; height: 58px;
right: -15px; bottom: 0;
}
#mario.frame_6 img {
background-position: -470px -24px;
width: 52px; height: 32px;
right: -37px; bottom: 0;
}
#mario.frame_7 img {
background-position: -562px -10px;
width: 26px; height: 58px;
right: -13px; bottom: 0;
}
<div id="controls">
<label>FPS <input id="fps" type="number" min="0" max="12"></label>
<label>Debug <input id="debug" type="checkbox"></label>
</div>
<div id="stage">
<div id="mario">
<img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7">
</div>
</div>