SpriteAnimationJS
by Mi_Creativity
HTML
<div id="monsterBG">Background</div><br><br>
<button id="bgBTNplay">Play</button>
<button id="bgBTNstop">Stop</button>
<hr>
<div id="monsterIMG">img tag
<img id="IMG" src="//i.stack.imgur.com/MJ8mZ.png">
</div>
<br><br>
<button id="imgBTNplay">Play</button>
<button id="imgBTNstop">Stop</button>
CSS
#monsterBG {
width: 190px;
height: 240px;
display:inline-block;
font-size:10px;
background: transparent url('//i.stack.imgur.com/MJ8mZ.png');
background-position:0 0;
}
#monsterIMG {
width: 190px;
height: 240px;
display:inline-block;
font-size:10px;
position:relative;
overflow:hidden;
}
#monsterIMG #IMG{
position:absolute;
top:0;
left:0;
}
JavaScript
var fullBGwidth = 1900,
fullIMGwidth = 1900,
step = 190, BGtimer, IMGtimer,
monsterBG = document.getElementById('monsterBG'),
BGplayBtn = document.getElementById('bgBTNplay'),
BGstopBtn = document.getElementById('bgBTNstop'),
monsterIMG = document.getElementById('IMG'),
IMGplayBtn = document.getElementById('imgBTNplay'),
IMGstopBtn = document.getElementById('imgBTNstop');
///// ---------- Background Images animation
BGplayBtn.addEventListener('click', playBgAnimation);
function playBgAnimation(){
BGplayBtn.setAttribute('disabled', true);
BGstopBtn.removeAttribute('disabled');
BGposX = monsterBG.style.backgroundPositionX;
BGposX = parseInt(BGposX) - step;
if(BGposX >= -fullBGwidth){
monsterBG.style.backgroundPositionX = BGposX.toString() + 'px';
} else {
monsterBG.style.backgroundPositionX = '0px';
}
BGtimer = setTimeout(playBgAnimation, 60);
}
BGstopBtn.addEventListener('click', function(){
clearTimeout(BGtimer);
monsterBG.style.backgroundPositionX = '0px';
BGplayBtn.removeAttribute('disabled');
BGstopBtn.setAttribute('disabled', true);
});
///// ---------- Image Tag animation
IMGplayBtn.addEventListener('click', playImgAnimation);
function playImgAnimation(){
IMGplayBtn.setAttribute('disabled', true);
IMGstopBtn.removeAttribute('disabled');
IMGposX = monsterIMG.style.left;
IMGposX = parseInt(IMGposX) - step;
if(IMGposX > -fullIMGwidth){
monsterIMG.style.left = IMGposX.toString() + 'px';
} else {
monsterIMG.style.left = '0';
}
IMGtimer = setTimeout(playImgAnimation, 60);
}
IMGstopBtn.addEventListener('click', function(){
clearTimeout(IMGtimer);
monsterIMG.style.left = '0px';
IMGplayBtn.removeAttribute('disabled');
IMGstopBtn.setAttribute('disabled', true);
});