其他分享
首页 > 其他分享> > HTML 入场动画(二)方格渐隐

HTML 入场动画(二)方格渐隐

作者:互联网

入场动画(二)

图片方格逐渐消失

  1. 实现逻辑:
    a: 将遮罩分割为数个div,多个div通过图片定位拼接成一张图片;
    b: 运用定时器+ animation实现动画;

  2. 效果:
    在这里插入图片描述

  3. 代码:

Document 内容
<script  type="text/javascript">
    function Render() {
        let r_this = this;
        let p_box = document.getElementById('maskBox');
        // 计算 方块个数
        let pWidth = p_box.offsetWidth,pHeight = p_box.offsetHeight;
        let num = parseInt(pWidth/100 * pHeight/100); // div个数:屏宽/div宽 * 屏高/div高
        let div = null,dX = 0,dY = 0,divHidden = null;
        let numArr = [],randomNum = 0,index = 0;
        //  创建DIV css精灵拼接图片
        r_this.createDiv = () => {
            for (let i=0;i<num;i++) {
                div = document.createElement("div");
                p_box.appendChild(div);
                dX = div.offsetLeft;
                dY = div.offsetTop;
                div.style['background-position']=''+(-dX)+'px '+(-dY)+'px';
                div.setAttribute('id','div_'+i)
                numArr.push(i);
            }
        }
        // 动画
        r_this.animation = () =>{
            // 随机隐藏
            randomNum = Math.floor(Math.random()*numArr.length);
            index = numArr.indexOf(randomNum);
            if (numArr.includes(randomNum)) {
                document.getElementById('div_'+randomNum).style.opacity = 0;
            } else {
                randomNum = Math.floor(numArr.length / 2);
                index = numArr.indexOf(randomNum);
                document.getElementById('div_'+randomNum).style.opacity = 0;
            }
            numArr.splice(index,1);
            // 关闭动画 
            if (numArr.length < 3) {
                p_box.remove(); // 清除遮罩
                window.cancelAnimationFrame(divHidden);
                divHidden = null;
                numArr = null;
                return;
            }

            divHidden = window.requestAnimationFrame(r_this.animation);
        }
    }
   // 创建方法
   var render = new Render();
   render.createDiv();
   // 延时开启动画展示
   setTimeout(function(){
        render.animation();
   },500)
</script>

标签:动画,渐隐,randomNum,divHidden,HTML,let,numArr,div
来源: https://blog.csdn.net/qq_38380311/article/details/114537821