当前位置:网站首页>requestAnimationFrame的应用

requestAnimationFrame的应用

2022-08-11 11:13:00 checkMa

requestAnimationFrame的应用

案例

何时启用 requestAnimationFrame,何时取消,下面是做了一个小案例。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style> .content{
       position: relative; } .content > span{
       position: absolute; width: 10px; height: 10px; border: 1px solid #bbb; padding: 10px; } </style>
</head>
<body>
    <div id="box">
        <button id="btn">click</button>
    </div>
    <div id="content" class="content">

    </div>
    <script> let list = []; let animating = null; btn.onclick =()=>{
       list.push({
       left: 0, top: 0 }); animating && window.cancelAnimationFrame(animating) animate() } function render(){
       let str = ""; for(let item of list ){
       if(item.left < 200){
       item.left += easeIn(item.left, 1, 0.02, 200); } if(item.top < 200){
       item.top += easeIn(item.top, 1, 0.02, 200); } if(item.top < 200 && item.left < 200){
       str += `<span style="left: ${
        item.left}px;top: ${
        item.top}px"></span>` } } list = list.filter(el=> (el.top < 200 && el.left < 200)); content.innerHTML = str; } function animate(){
       render(); if(list.length > 0){
       animating = window.requestAnimationFrame(animate) } } function linear(speed){
       return speed; } function quicken(value, speed, factor){
       return speed + value * factor; } function easeIn(value, speed, factor, max){
       if(value < max/2){
       return speed + value * factor; }else{
       return speed + ( max - value ) * factor; } } </script>
</body>
</html>
原网站

版权声明
本文为[checkMa]所创,转载请带上原文链接,感谢
https://blog.csdn.net/qq_36990322/article/details/126252708