我的第一篇博客:requestAnimationFrame学习笔记

时间:2022-10-01 05:14:55

通常,我们在浏览器中写动画会用到哪些技术呢?

flash

  可以实现一些非常复杂的动画,但随着HTML5的成熟,个人感觉flash终究会成为明日黄花。

css3

  当前大部分现代浏览器已经对css3支持的很好了。通过transform实现2D/3D转换,通过transition实现元素过渡效果,使用animation与keyframes搭配实现复杂动画。而且用css3写动画还有个优点就是不会报错,我们写脚本的时候常常会出现语法错误,但css不会,大不了浏览器不认识规则不起作用呗(PS:有需要支持ie6等古董级浏览器的同学,使用HTML5和CSS3的新属性时,可以去这个网站 http://caniuse.com/ 查一查你要用的新特性在各主流浏览器及浏览器各版本中的支持情况,可以提高工作效率哦)

js定时器setTimeout/setInterval

  可以通过设置定时器通过循环来使html元素动起来~这个大家都会用滴

  但,今天要出场的是HTML5的requestAnimationFrame。

  第一感觉,名字好长,翻译过来貌似就是“请求动画帧”。它有什么优点呢?HTML5推出这个API主要是为了优化动画性能的。

  怎么说呢,fps(画面每秒传输帧数)对于很多显示器都是60,对应显示频率就是16.7ms/次。所以设置定时器时如果时间间隔低于这个数值,某些帧是无法绘制的,就会造成所谓“过渡绘制”了,可能还会影响应用的性能。而requestAnimationFrame跟着浏览器的绘制间隔走,不会过渡绘制,资源高效利用,自然流畅~各大浏览器支持也比较好(详见:http://caniuse.com/#search=requestanimationframe)

  多说无益,上代码看看吧:

  

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>An Example:requestAnimationFrame&amp;canvas</title>
<style type="text/css">
html{
background: #000;
}
</style>
</head>
<body>
<script>
(function(){
window.requestAnimationFrame=  //兼容处理
window.requestAnimationFrame||
window.webkitRequestAnimationFrame||
window.mozRequestAnimationFrame||
window.oRequestAnimationFrame||
window.msRequestAnimationFrame||
function(callback,element){
window.setTimeout(callback,1000/60);
};
var canvas,context,toggle;
init();
animate(); function init(){
canvas=document.createElement("canvas");
canvas.width=512;
canvas.height=512;
context=canvas.getContext("2d");
document.body.appendChild(canvas);
}
function animate(){
requestAnimationFrame(animate);  //requestAnimationFrame需要递归调用才能实现连续的动画
draw();
}
function draw(){
var time=new Date().getTime()*0.002;
var x=Math.sin(time)*192+256;
var y=Math.cos(time*0.9)*192+256;
toggle=!toggle; context.fillStyle=toggle?'rgb(200,200,20)':'rgb(20,20,200)';
context.beginPath();
context.arc(x,y,10,0,Math.PI*2,true);
context.closePath();
context.fill();
}
})();
</script>
</body>
</html>

这个例子还涉及到canvas画图,顺便把canvas api也给巩固一下,嘻嘻

reference:

http://www.webhek.com/requestanimationframe/

http://www.zhangxinxu.com/wordpress/tag/requestanimationframe/