js用setInterval定时器实现帧动画效果

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<style type="text/css">
			body{
				text-align: center;
			}
			img{
				padding-top: 100px;
			}
		</style>
		<script type="text/javascript">
			window.onload = function(){
				var img = document.querySelector('img');
				var audio = document.querySelector('audio');
				var btn = document.querySelector('button');
				var arr = [];
				for(var i=1 ; i<12; i++){
					arr.push('./images/a'+i+'.jpg');
				}
				// console.log(arr)
				var timer = null,nf = true,i = 1;
				btn.onclick = function(){
					clearInterval(timer);
					if(nf){
						timer = setInterval(function(){
							i++;
							if(i >= arr.length){
								i = 1;
							}
							img.src = arr[i];
						},20);
						audio.play();
						btn.innerText = '停,驭';
					}else{
						audio.pause();
						btn.innerText = '跑,驾';
					}
					nf = !nf;
				}
			}
		</script>
	</head>
	<body>
		<img src="./images/a1.jpg" alt="t"><br>
		<audio src="./images/ma.mp3" loop>
			当前浏览器不支持audio
		</audio>
		<button type="button">跑,驾</button>
	</body>
</html>

 

posted @ 2020-03-28 15:24  JackieDYH  阅读(2)  评论(0编辑  收藏  举报  来源