Javascript动画不流畅?

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>

这是我的代码,我想问的是:

  1. 为什么图像不流畅??我说动画就像每隔几秒刷新一次
  2. 鼠标悬停(onMouseOver)时如何让图片移动?

你只需要改变条件,因为定位器在图像的空白部分。现在定位器在显示空部分之前变为 0。如果你不想要闪烁的gif,你需要设置positioner <= length of image

var positioner=0;
var ames=setInterval(animate, 100);
function animate(){
if(positioner <= 1000){
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>

注意:你的第一个问题的答案是——你的动画设置为100但是你在动画ends/starts时的位置是1536 改为 1000.

第二个问题 - 试试这个:

<img onmouseout="animate(this)" onmouseout="dontAnimate(this)" src="smiley.gif" alt="Smiley">
function dontAnimate() {
 // Do your thingy!
 // Stop the animation
};

通过放慢速度,很明显您在最后显示了一个空帧。如果您更改代码以在渲染每个循环后评估 positioner 是否超过最大值,这将为您修复它。

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>