那么有了这个steps(),我们就可以实现web中常见的Sprite 精灵动画了,见demo:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>CSS3 spirit精灵动画</title>
<style>
.bird{background: url(http://www.cj365.cc/demo/bird/bird.png);width: 140px;height:85px;animation: bird 2s steps(8) infinite;position: absolute;top: 50%;left: 50%;margin-top: -43px;margin-left: -70px;}
@keyframes bird{
from {
background-position: 0 0;
}
to {
background-position: -800% 0px;
}
}
</style>
</head>
<body>
<div class="bird"></div>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>canvas帧--实现动画</title>
<style>
*{padding:0;margin:0;}
canvas{display:block;background:white}
</style>
</head>
<body>
<canvas></canvas>
<script>
var imgPic = new Image();
imgPic.src = 'http://www.cj365.cc/demo/bird/bird.png';
var canvas = document.querySelector('canvas');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
var ctx = canvas.getContext('2d');
imgPic.onload = function () {
drawImg()
}
var i = 0;
var lastTime = new Date().getTime();
var delatime;
var timer = 0;
function drawImg() {
window.requestAnimationFrame(drawImg);
var now = new Date().getTime();
delatime = now - lastTime;
lastTime = now;
timer += delatime;
if (timer > 200) {
i++;
if (i > 7) i = 0;
timer = 0
}
console.log(delatime)
ctx.drawImage(imgPic, i * 140, 0, 140, 85, (canvas.width - 140) / 2, (canvas.height - 85) / 2, 140, 85);
}
</script>
</body>
</html>