canvas粒子效果

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>

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,015评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,262评论 1 292
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,727评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,986评论 0 205
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,363评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,610评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,871评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,582评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,297评论 1 242
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,551评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,053评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,385评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,035评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,079评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,841评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,648评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,550评论 2 270

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 170,569评论 25 707
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 11,613评论 4 59
  • 我的CD 作为一个独立的工程师,时间是最宝贵的,搭建一个高效的产品发布环境能节省很多重复的时间。现在有很多这样的C...
    MR__Fan阅读 407评论 0 2