标签:onload 暂停 block term canvas 等等 isp get oss
在web开发中,GIF动画效果是随处可见,比如常见的loading加载、人物奔跑的gif图片等等,那么这些都是怎么实现的呢?利用canvas的drawImage把含有帧的图片加载到canvas中去,再结合js实现动画
<!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>
以上方法实现的前提是,需要有一张已绘制帧的图片,有了图片才可进行帧的动画;利用该方法可以控制动画的播放、暂停以及帧率
标签:onload 暂停 block term canvas 等等 isp get oss
原文地址:http://blog.51cto.com/14071672/2316867