canvas粒子效果

2017-06-09  本文已影响0人  adtk
image.png image.png
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        *{margin:0;padding: 0;border:0;}
        canvas{
            position: fixed;
            top: 0;
            left: 0;
        }
    </style>
</head>

<body>
    <canvas id="canvas" width="500" height="500"></canvas>

    <script type="text/javascript">
(function(win, doc) {
    function particleFn(el) {
        var _this = this;

        var vendors = ['ms', 'moz', 'webkit', 'o'];
        for (var x = 0; x < vendors.length && !win.requestAnimationFrame; ++x) {
            win.requestAnimationFrame = win[vendors[x] + 'RequestAnimationFrame'];
            win.cancelAnimationFrame = win[vendors[x] + 'CancelAnimationFrame'] || win[vendors[x] + 'CancelRequestAnimationFrame'];
        }

        function arcData() { //生成每个粒子的参数
            this.x = parseInt(Math.random() * (_this.width));
            this.y = parseInt(Math.random() * (_this.height));
        
            //半径由初始先变最大,再变最小
            this.r = parseInt(Math.random() * 5); //半径,初始半径
            this.minR = Math.random() * 5; //半径,最小半径
            this.maxR = Math.random() * (this.r) + 5; //最大半径
            this.flagR = false;

            this.directionx = parseInt(Math.random() * 2); //0,1表示运动方向
            this.directiony = parseInt(Math.random() * 2);

            this.speedx = Math.random() * 0.3 * (_this.speed || 1) + 0.05; //运动速度,0.05是防止速度=0
            this.speedy = Math.random() * 0.3 * (_this.speed || 1) + 0.05;

            // 定义color为rgb;
            this.color = _this.color[parseInt(Math.random() * _this.color.length)] || '#8a7b7b';

            this.rgb = {
                r: parseInt(Math.random() * 255),
                g: parseInt(Math.random() * 255),
                b: parseInt(Math.random() * 255),
                a: 0.5,
                minA: Math.random(), //最小透明度
                flag: true, //true表示该减了
            }
            this.lineColor = _this.lineColor[parseInt(Math.random() * _this.lineColor.length)] || '#9a8686';
        }
        this.drawArc = function(arc, index) { //画圆
            _this.cxt.beginPath();
            _this.cxt.arc(arc.x, arc.y, arc.r, 0, 2 * Math.PI);
            // 颜色
            if (_this.color.length > 0) {
                _this.cxt.fillStyle = arc.color;
            } else {
                _this.cxt.fillStyle = 'rgba(' + arc.rgb.r + ',' + arc.rgb.g + ',' + arc.rgb.b + ',' + arc.rgb.a + ')';
                if (arc.rgb.flag) {
                    arc.rgb.a -= 0.005;
                    if (arc.rgb.a <= arc.rgb.minA) {
                        arc.rgb.flag = false;
                    }
                } else {
                    arc.rgb.a += 0.01;
                    if (arc.rgb.a >= 1) {
                        arc.rgb.flag = true;
                    }
                }
            }

            if (arc.flagR) { //圆的半径变化
                arc.r -= 0.01;
                if (arc.r <= arc.minR) {
                    arc.flagR = false;
                }
            } else {
                arc.r += 0.05;
                if (arc.r >= arc.maxR) {
                    arc.flagR = true;
                }
            }

            _this.cxt.fill(); //画空心圆
            _this.cxt.closePath();

            //超出canvas就删除
            if (arc.x > _this.width + arc.r || arc.y > _this.height + arc.r || arc.x < 0 - arc.r || arc.y < 0 - arc.r) {
                this.arcArr.splice(index, 1) //[i];
            }
        }
        this.drawLine = function(arc, nextArc) { //连线
            //直角三角形中,x的平方+y的平方=z的平方,求平方根:Math.sqrt(9)==3
            // arc.x - nextArc.x求得是x坐标的差,arc.y - nextArc.y求的是y坐标的差,两个值是直角的两边,第三边就是距离。。。
            var distance = Math.sqrt((arc.x - nextArc.x) * (arc.x - nextArc.x) + (arc.y - nextArc.y) * (arc.y - nextArc.y));
            if (distance < _this.maxLine) { //小于_this.maxLine距离的连线
                _this.cxt.beginPath();
                _this.cxt.moveTo(arc.x, arc.y);
                _this.cxt.lineTo(nextArc.x, nextArc.y);
                _this.cxt.lineWidth = 1;
                _this.cxt.strokeStyle = arc.lineColor;
                _this.cxt.stroke();
            }
        }
        this.mouseX = 0;
        this.mouseY = 0;
        this.mouseLine = function(nextArc) { //鼠标连线
            if (this.mouseX && this.mouseY) {
                this.drawLine({
                    x: this.mouseX,
                    y: this.mouseY,
                    lineColor: _this.mouseLineColor[parseInt(Math.random() * _this.mouseLineColor.length)] || '#8a7b7b'
                }, nextArc)
            }
        }
        this.shove = function(nextArc) { //推移
            if ((nextArc.x < _this.mouseX + _this.Maxshove && nextArc.x > _this.mouseX - _this.Maxshove) && (nextArc.y < _this.mouseY + _this.Maxshove && nextArc.y > _this.mouseY - _this.Maxshove)) {

                if (nextArc.x < _this.mouseX + _this.Maxshove && nextArc.x > _this.mouseX - _this.Maxshove) {
                    nextArc.directionx = nextArc.directionx ? 0 : 1;
                    if (nextArc.x < _this.mouseX) {
                        nextArc.x -= 1;
                    } else {
                        nextArc.x += 1;
                    }
                }
                if (nextArc.y < _this.mouseY + _this.Maxshove && nextArc.y > _this.mouseY - _this.Maxshove) {
                    nextArc.directiony = nextArc.directiony ? 0 : 1;
                    if (nextArc.y < _this.mouseY) {
                        nextArc.y -= 1;
                    } else {
                        nextArc.y += 1;
                    }
                }
            }
        }
        this.move = function(arc) { //移动
            if (!arc) {
                return
            }
            if (arc.directionx) {
                arc.x += arc.speedx;
            } else {
                arc.x -= arc.speedx;
            }
            if (arc.directiony) {
                arc.y += arc.speedy;
            } else {
                arc.y -= arc.speedy;
            }
        }
        this.draw = function() {
            _this.cxt.clearRect(0, 0, _this.width, _this.height);

            for (var i = 0; i < _this.arcArr.length; i++) {
                if (_this.showLine) {
                    for (var k = i + 1; k < _this.arcArr.length; k++) {
                        _this.drawLine(_this.arcArr[i], _this.arcArr[k]);
                    }
                }
                if (_this.showMouseLine) {
                    _this.mouseLine(_this.arcArr[i]);
                }
                if (_this.isShove) {
                    _this.shove(_this.arcArr[i]);
                }
                _this.move(_this.arcArr[i]);
                _this.drawArc(_this.arcArr[i], i); //传递下标i是为了删除
            }
        }
        this.stop = function() {
            cancelAnimationFrame(_this.requestId);
            return true
        }
        this.start = function() { //生成粒子

            cancelAnimationFrame(_this.requestId);
            if (_this.arcArr) {
                for (var i = _this.arcArr.length; i < _this.num; i++) {
                    _this.arcArr.push(new arcData());
                }
                _this.draw();
            }
            _this.requestId = requestAnimationFrame(_this.start);
        }
        var timeout = null;
        this.init = function(initData) {
            clearTimeout(timeout);
            timeout = setTimeout(function() { //避免多次init初始化
                cancelAnimationFrame(_this.requestId);
                if (!initData || !initData.el) {
                    _this.el = document.getElementById(el);
                    _this.cxt = _this.el.getContext("2d");
                    _this.width = _this.el.width; //canvas宽高
                    _this.height = _this.el.height;
                }
                _this.num = 30; //粒子数量,默认30
                _this.color = []; //粒子颜色,默认随机
                _this.showLine = true;
                _this.maxLine = 50; //连线距离
                _this.lineColor = ['#8a7b7b']; // 默认

                _this.showMouseLine = true; //显示鼠标连线
                _this.mouseLineColor = ['red']; //鼠标连线颜色

                _this.isShove = true;
                _this.Maxshove = 50;

                for (var i in initData) {
                    if (initData.hasOwnProperty(i)) {
                        _this[i] = initData[i];
                        if (i == 'el') {
                            _this.el = document.getElementById(initData[i]);
                            _this.cxt = _this.el.getContext("2d");
                            _this.width = _this.el.width; //canvas宽高
                            _this.height = _this.el.height;
                        }
                    }
                }
                _this.el.onmousemove = function(e) {
                    // 这个得改,需要获取鼠标在canvas上的位置
                    _this.mouseX = e.layerX;
                    _this.mouseY = e.layerY;
                    console.log(e.layerX, e.layerY);
                }
                _this.el.onmouseout = function(e) {
                    _this.mouseX = 0;
                    _this.mouseY = 0;
                    console.log(e.layerX, e.layerY);
                }

                _this.arcArr = []; //所有粒子存放的数组
                _this.start();
                console.log(_this);
            }, 200)
        }
    }
    win.particle = particleFn;
})(window, document)


        document.getElementById('canvas').width=document.documentElement.clientWidth;
        document.getElementById('canvas').height=document.documentElement.clientHeight;
        var c = new particle("canvas");//接受一个canvas的id:必填
            c.init();
            c.init({//初始化,接受一个对象,所有属性可选
                el:"canvas",//可以替换new方法中的id,可选
                num:200,//粒子数量,默认30
                color:[],//粒子颜色,默认随机
                lineColor:[],//若不传递值,连线颜色默认['#8a7b7b']
                
                speed:2,//1为正常移动速度
                showLine:true,//显示连线,默认true
                
                showMouseLine:true,//showLine必须为true
                mouseLineColor:[],
                
                isShove:true,//是否推动
                Maxshove:50,//推动距离

                maxLine:60,//链接线的最大长度,默认50
            })
            c.stop();//停止动画
            c.start();//停止动画
    </script>
</body>

</html>

可以实现鼠标推移粒子,连线粒子,鼠标连线粒子,自定义颜色

上一篇下一篇

猜你喜欢

热点阅读