实现更高级的动画效果—requestAnimationFrame

分类栏目:用户体验 - 前端开发

3168

发布于 暂无评论

我们一般用 H5 的transitionanimations可能实现动画效果,但是高质量的动画效果及其流畅度都要求极致怎么办呢?

接下来引入正题:

浏览器提供了一个统一帧管理、提供监听帧的API,​既requestAnimationFrame();

//简单的浏览器兼容(监听动画帧API);
window.requestAnimFrame = (function() {
    return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame ||
        function( /* function FrameRequestCallback */ callback, /* DOMElement Element */ element) {
            return window.setTimeout(callback, 1000 / 60);
        };
})();

requestAnimationFrame 函数只是一个做动画基础的API,既不基于DOM元素的style变化,也不基于canvas。

更多详情请参考:requestAnimationFrame for Smart Animating

​CSS代码:

html { background: #000; }

javaScript代码:

//简单的浏览器兼容(监听动画帧API)
window.requestAnimFrame = (function() {
    return window.requestAnimationFrame ||
        window.webkitRequestAnimationFrame ||
        window.mozRequestAnimationFrame ||
        window.oRequestAnimationFrame ||
        window.msRequestAnimationFrame ||
        function( /* function */ callback, /* DOMElement */ element) {
            window.setTimeout(callback, 1000 / 60);
        };
})();

var canvas, context, toggle;
init();
animate();

function init() {
    canvas = document.createElement('canvas');
    canvas.width = 620;
    canvas.height = 620;
    context = canvas.getContext('2d');
    document.body.appendChild(canvas);
}

function animate() {
    requestAnimFrame(animate); //引入浏览器兼听帧
    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();
}

扩展阅读:

http://www.zhangxinxu.com/wordpress/?p=3695
http://www.paulirish.com/2011/requestanimationframe-for-smart-animating/
http://mrdoob.com/lab/javascript/requestanimationframe/