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

入场动画(二)

图片方格逐渐消失

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

  2. 效果:
    HTML 入场动画(二)方格渐隐

  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>
上一篇:怎样使用 Svelte 中的异步块


下一篇:在canvas绘制的画布上实现一个动态小球碰撞;拓展:简单更改即可实现矩形碰撞