Search code examples
javascripthtmlanimationeventssprite-sheet

Javascript Animation Not Smooth?


var positioner=0;
var ames=setInterval(animate, 100);
function animate(){
if(positioner < 1536){
document.getElementsByTagName('img')[0].style.backgroundPosition='-'+positioner+'px';positioner += 256;}
else{document.getElementsByTagName('img')[0].style.backgroundPosition='-'+positioner+'px'; positioner=0;}
}
img { 
    background-image: url('https://cdn-images-1.medium.com/max/1600/1*WhDjw8GiV5o0flBXM4LXEw.png');
    background-repeat: no-repeat;
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<img width="256px" height="256px" onmouseover=""/>
<h1>The background-position Property</h1>
<p>Here, the background image will be positioned in the center of the element (in this case, the body element).</p>
</html>

That's my code, and what i want to ask is:

  1. why the image not smooth?? I say the animation is like refreshing every some of seconds
  2. how to make the image moving when the MouseOver (onMouseOver)?

Solution

  • By slowing it down, it was apparent that you were showing an empty frame at the end. If you change your code to evaluate whether or not positioner is over the max after rendering each loop, that will fix it for you.

    var positioner=0;
    var ames=setInterval(animate, 100);
    function animate(){
      document.getElementsByTagName('img')[0].style.backgroundPosition='-'+positioner+'px';
      positioner += 256;
      if(positioner >= 1536) positioner = 0
    }
    img { 
        background-image: url('https://cdn-images-1.medium.com/max/1600/1*WhDjw8GiV5o0flBXM4LXEw.png');
        background-repeat: no-repeat;
    }
    <img width="256px" height="256px" onmouseover=""/>
    <h1>The background-position Property</h1>
    <p>Here, the background image will be positioned in the center of the element (in this case, the body element).</p>