我尝试了很多不同的东西,似乎什么都没有用,所以我希望这里的某个人有空闲时间并希望得到帮助。我正在尝试为一个sprite strip的动画创建javascript,其中有11个图像垂直堆叠,每个帧为640 x 889.我希望动画在窗口打开时来回启动并来回穿过帧3次然后停止。序列应该有11帧1 .... 11然后11 ... 1,三次并总共花费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");
}
答案 0 :(得分:0)
您的问题是未定义requestAnimationFrame。它没有被所有浏览器实现。
我找到了一个垫片here
// 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);
};
})();
并更新了您的fiddle
现在它有所作为,但我不认为这正是你的想法!
答案 1 :(得分: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的图像会缩小,这就是为什么会这样。