0

我尝试了很多不同的东西,但似乎没有任何效果,所以我希望这里有人有空闲时间并想提供帮助。我正在尝试为精灵条的动画创建 javascript,该动画具有 11 个垂直堆叠的图像,每帧为 640 x 889。我希望动画在窗口打开时开始并在帧中来回运行 3 次然后停止. 有 11 帧,序列应该是 1....11 然后 11...1,3 次,总共需要 3 秒来完成三个循环。在此先感谢您的帮助。

HTML:

<!DOCTYPE html>
<html>
<head>
    <script src="jquery-1.8.2.js"></script>
    <meta name ="viewport" content = "width=640, user-scalable=yes">
    <link rel="stylesheet" href="animate.css"/>
    <title>Website</title>
</head>
<body>
    <div id="bmw-glow">
    <script type="text/javascript">
    var fps          = 11,
    currentFrame = 0,
    totalFrames  = 11,
    elem         = document.getElementById("bmw-glow"),
    currentTime  = new Date().getTime();

(function animloop(time){
  var delta = (time - currentTime) / 1000;

  currentFrame += (delta * fps);

  var frameNum = Math.floor(currentFrame);

  if (frameNum >= totalFrames) {
    currentFrame = frameNum = 0;
  }

  requestAnimationFrame(animloop);

  elem.style.backgroundPosition = "0 -" + (frameNum * 889) + "px";

  currentTime = time;
})(currentTime);
</script>
</div>
</body>
</html>

CSS:

#bmw-glow {
  width: 640px;
  height: 889px;
  margin: 0px;
  background: url("images/Social/Social_6_S.jpg");
}
4

2 回答 2

0

你的问题是 requestAnimationFrame 没有定义。并非所有浏览器都实现了它。

我在这里找到了一个垫片

    // shim layer with setTimeout fallback
window.requestAnimFrame = (function(){
  return  window.requestAnimationFrame       || 
          window.webkitRequestAnimationFrame || 
          window.mozRequestAnimationFrame    || 
          window.oRequestAnimationFrame      || 
          window.msRequestAnimationFrame     || 
          function( callback ){
            window.setTimeout(callback, 1000 / 60);
          };
})();

并更新了你的小提琴

现在它做了一些事情,但我不认为这正是你的想法!

于 2012-11-02T21:41:18.917 回答
0

扩展马特的答案:http: //jsfiddle.net/Shmiddty/xtQDn/5/

首先,您需要“屏蔽”动画,以便一次只能看到一帧。为此,只需将容器的宽度和高度设置为一帧的大小:

#bmw-glow {
  width: 104px;
  height: 144.45px; /* Fractional pixels are not good. */
  margin: 0px;
  background: url("http://i45.tinypic.com/4qj0b5.jpg") no-repeat;
}

其次,我修改了使我们当前帧为绝对正弦波的代码。这给了我们一点放松,这可能不是所有情况都需要的,但我认为这种情况很好。

var freq     = 1,  //frequency of the animation. Roughly how many times per second it should loop. Higher number is faster, lower number is slower.
currentFrame = 0,
totalFrames  = 11,
deltaFrame   = 1,
frameStep    = 1589 / totalFrames,
elem         = document.getElementById("bmw-glow"),
currentTime  = new Date().getTime();

(function animloop(time){
  var delta = (time - currentTime) / 1000;

  currentFrame += (delta);

  var frameNum = Math.floor(Math.abs(Math.sin(currentFrame*freq) * totalFrames));

  requestAnimFrame(animloop);

  elem.style.backgroundPosition = "0 -" + (frameNum * frameStep) + "px";

  currentTime = time;
})(currentTime);

显然,在这个例子中,有一些抖动,因为我们正在处理小数像素。我相信您上传到 tinypic 的图片已按比例缩小,这就是发生这种情况的原因。

于 2012-11-05T15:48:27.733 回答