运动

速度版运动:

  通多改变 left 或者 top 值,来实现运动,主要控制速度。

 let num = 0;
 setInterval(()=>{
     num += 5;
     box.style.left = num + 'px';
 },16.7);

/*起始位置以(每16.7毫秒运动5px)的速度运动*/
setInterval(()=>{
     box.style.left = box.offsetLeft + 5 + 'px';
 },16.7);

时间版运动:

  已用的时间 / 总时间 * 总路程 + 其实的位置 = 当前时间应该出现的位置

  t:time 已过的时间

  b:begin 起始值

  c:count 总的运动值

  d:duration 持续的时间

  box.style.left = t / d * c + b

   let timer = null;
   let duration = 10000;
   let count = 500;
   
   document.onclick = ()=>{
        let old = new Date;
        let begin = parseFloat(getComputedStyle(box).left);
        count = count-begin;
        timer = setInterval(()=>{
            let t = new Date - old;
            // if(t >= duration){
            //     box.style.left = count + 'px';
            //     clearInterval(timer);
            // }else{
            //     box.style.left =  t/duration * count + 'px';
            // }  

            if(t >= duration)t = duration;
            box.style.left = t/duration * count + begin + 'px';
            if(t === duration){
                clearInterval(timer);
            } 
        },16.7);
   }

帧运动:

requestAnimationFrame采用系统时间间隔,保持最佳绘制效率,
不会因为间隔时间过短,造成过度绘制,增加开销;也不会因为间隔时间太长,
使用动画卡顿不流畅,让各种网页动画效果能够有一个统一的刷新机制,
从而节省系统资源,提高系统性能,改善视觉效果

requestAnimationFrame(运动函数)

返回值为 number(编号)

cancelAnimationFrame(编号)关闭动画帧

例子:帧运动做一个计时器,点击屏幕时停止。
    (function move(){
        let timer = requestAnimationFrame(move);
        let date = new Date();

        box.innerHTML = date.getFullYear() +'年'+(date.getMonth()+1) +'月'+date.getDate() + '日' + date.getHours() +':'+date.getMinutes() + ':'+date.getSeconds();

        document.onclick = function(){
            cancelAnimationFrame(timer);
        }
        
    })();

猜你喜欢

转载自www.cnblogs.com/MrZhujl/p/9966676.html