当前位置:首页 > canvas绘制一个加载中的动画

canvas绘制一个加载中的动画

发布于 2018-07-16 阅读 125 次 Canvas Javascript

介绍:

一个canvas绘制的水波效果的正在加载动画效果。颜色随机设置的;每次进来颜色都不一样。

预览:

loading预览

使用方式

window.onload = function(){
    var l = new LoadAnim({id: 'canvas'});
    l.init();
}

源代码

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        body,html,canvas{padding:0;margin:0;}
        canvas{display:block;}
    </style>
</head>
<body>
    <canvas id='canvas'>您的浏览器不支持</canvas>
</body>
</html>
<script>
    function LoadAnim(opt){
        this.circles = []; //圆半径
        this.w = window.innerWidth,
        this.h = window.innerHeight;

        this.num = opt.num?opt.num:5; // 圆形的数量
        this.dis = opt.dis?opt.dis:1; //加速度
        this.rgb = opt.rgb?opt.rgb:'';
        this.el = document.getElementById(opt.id);

        this.ctx = this.el.getContext('2d');
        this.el.width = this.w;
        this.el.height = this.h;
        this.r = opt.r?opt.r:this.w/5;
    }
    LoadAnim.prototype.init = function(){
        this.makeCircles();
        this.loop();
    }
    LoadAnim.prototype.makeCircles = function(){
        this.rgb = this.rgb?this.rgb:getRandColor();
        for(var i=this.num;i>-1;i--){
            var c = {
                    r: this.r/this.num*i,
                    alpha:(1/this.r) * this.r/this.num
                };
            this.circles.push(c)
        }
    }

    LoadAnim.prototype.drawCircle = function(){
        for(var i=0;i<this.num+1;i++){
            this.ctx.beginPath();
            this.ctx.fillStyle = "rgba("+this.rgb.r+","+this.rgb.g+","+this.rgb.b+","+this.circles[i].alpha+")";
            this.ctx.arc(this.w/2, this.h/2, this.circles[i].r, 0, 2*Math.PI);
            this.ctx.fill();
        }
    }

    LoadAnim.prototype.loop = function(){
        var _this = this;
        window.requestAnimationFrame(function(){_this.loop();});
        this.ctx.clearRect(0, 0, this.w, this.h);
        this.drawCircle(this.rgb);
        for(var i=0;i<this.num+1;i++){
            if(this.circles[i].r > this.r){
                this.circles.splice(i, 1);
                this.circles.push({r: 0, alpha:0});
            } else {
                this.circles[i].r += this.dis;
                this.circles[i].alpha = 1 - (1/this.r) * this.circles[i].r;
            }
        }
    }

    function getRandom(min, max){
        return Math.floor((max-min)*Math.random() + min);
    }

    function getRandColor(){
        var r = getRandom(0, 255),
            g = getRandom(0, 255),
            b = getRandom(0, 255);
        var rgb = {
            r: r,
            g: g,
            b: b
        }
        return rgb;

    }

    window.onload = function(){
        var l = new LoadAnim({id: 'canvas'});
        l.init();
    }
</script>