前端学习笔记--requestAnimationFrame优化动

2018-11-11  本文已影响0人  沧澈

requestAnimationFrame,顾名思义就是请求动画帧,是html5 提供一个专门用于请求动画的API,当需要更新屏幕画面时就可以调用此方法。

example
css:
--------------------------------------
<style>
    div{
        width: 100px;
        height: 100px;
        background-color: red;
    }
</style>
--------------------------------------
html:
<div id="SomeElementYouWantToAnimate"></div>
--------------------------------------
 js:
<script>
    var start = null;
    var element = document.getElementById('SomeElementYouWantToAnimate');
    element.style.position = 'absolute';

    function step(timestamp) {
        // timestamp时间戳
        if (!start) start = timestamp;
        var progress = timestamp - start;
        element.style.left = Math.min(progress / 10, 200) + 'px';
        if (progress < 2000) {
            window.requestAnimationFrame(step);
        }
    }

    window.requestAnimationFrame(step);
</script>

上一篇 下一篇

猜你喜欢

热点阅读