JS_Loading加载动画

JS_Loading加载动画

  • 效果比较简单,看图吧

    loading.gif
  • Ball.js

    创建外部的Class文件,一会在下面引入

    export default class Ball {
        angle = 0;
        speed = 4;
        radius = 40;
        constructor(r, c) {
            this.elem = this.createElem(r, c);
        }
        // 创建每一个小圆点
        createElem(r, c) {
            if (this.elem) return this.elem;
            let div = document.createElement("div");
            Object.assign(div.style, {
                width: r * 2 + "px",
                height: r * 2 + "px",
                backgroundColor: c,
                borderRadius: r + "px",
                position: "absolute"
            });
            return div;
        }
        // 设置透明度递减
        alpha(_alpha) {
            this.elem.style.opacity = _alpha;
        }
        setPosition(x, y) {
            this.x = x;
            this.y = y;
        }
        appendTo(parent) {
            parent.appendChild(this.elem);
        }
        update(i) {
            this.angle += this.speed;
            if (this.angle === 360) this.angle = 0;
            var speedX = Math.sin(this.angle * Math.PI / 180) * this.radius;
            var speedY = Math.cos(this.angle * Math.PI / 180) * this.radius;
            this.elem.style.left = this.x + speedX + "px";
            this.elem.style.top = this.y + speedY + "px";
        }
    }
    
    
  • HTML页面引入JS

    import Ball from "./js/Ball.js";
    //创建数组,在动画函数中,通过forEach更新每个小球的位置
    let arr = [];
    var i = 0;
    var num = 10; //初始化小球的个数
    var time = 0;
    init();
    function init() {
        setInterval(animation, 16);
    }
    
    function animation() {
        createBall();
        arr.forEach(function (item) {
            item.update(i);
        })
    }
    
    function createBall() {
        if (i > num) return;
        time --;
        if (time > 0) return;
        time = 8;
        i++;
        //Class的参数(小球的半径,颜色)
        let b = new Ball(num - i, "#222");
        b.appendTo(document.body);
        // 设置透明度递减
        b.alpha((num - i/2) / 10);
        //设置小球做圆周运动的圆心
        b.setPosition(300, 300);
        arr.push(b);
    }
    
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容