sa.lva.ge sa.lva.ge - 5 months ago 13
Javascript Question

Javascript Code Not Looping

Hi Everyone I been animating a sprite using only javascript & css techniques it animate but it wont do any looping. When it reach the end of the image it turns into a blank image already.

Here's my code:

<html>
<head>
<style type="text/css">
.container
{
width: 512px;
height: 512px;
overflow: hidden;
}
</style>

<script type='text/javascript'>
document.onreadystatechange = function ()
{
if (document.readyState == "complete")
{
setInterval(next, 100);
}
else
{
return false;
}
}

var frame = 1;

function next()
{
var left = 512 * frame;
var top = 0;
var elementStyle = document.getElementById('image').style;

elementStyle.position = "relative";
elementStyle.top = '-'+top+'px';
elementStyle.left = '-'+left+'px';

frame++;
}
</script>
</head>
<body>
<div class="container">
<img id="image" src="flame_sprite.png" />
</div>
</body>
</html>


This is the picture I'm using to test the code:

http://www.thecave.info/wp-content/uploads/2014/08/flame_sprite.png

Kindly Explain to me what is wrong on my code also if someone can help me fixed it I'm very thankful.

Answer

You have 6 frames on your picture, you must loop on it, add if(frame == 6 ) frame = 0; to restart your animation.

function next()
{
    if(frame == 6 ) frame = 0;

    var left = 512 * frame;

    var top = 0;

    var elementStyle = document.getElementById('image').style;

    elementStyle.position = "relative";

    elementStyle.top = '-'+top+'px';

    elementStyle.left = '-'+left+'px';

    frame++;

 }

Show result : http://jsfiddle.net/59yhuk8L/

Comments