很漂亮的一个背景控件——ribbons.js
写博客的人都喜欢优化自己的博客主页,博主也一样,找了一些背景控件,像canvas-nest.js等等,最终选择了ribbons.js,并基于源码,稍作了一丁点的修改,这里分享出来
    (function (name, factory) {
        if (typeof window === "object") {
            window[name] = factory();
        }
    })
        ("Ribbons", function () {
            var _w = window, _b = document.body, _d = document.documentElement;
            //随机函数
            var random = function () {
                if (arguments.length === 1) {
                    if (Array.isArray(arguments[0])) {
                        var index = Math.round(random(0, arguments[0].length - 1));
                        return arguments[0][index];
                    }
                    return random(0, arguments[0]);
                } else
                    if (arguments.length === 2) {
                        return Math.random() * (arguments[1] - arguments[0]) + arguments[0];
                    }
                return 0;
            };
            //屏幕信息
            var screenInfo = function (e) {
                var width = Math.max(0, _w.innerWidth || _d.clientWidth || _b.clientWidth || 0),
                    height = Math.max(0, _w.innerHeight || _d.clientHeight || _b.clientHeight || 0),
                    scrollx = Math.max(0, _w.pageXOffset || _d.scrollLeft || _b.scrollLeft || 0) - (_d.clientLeft || 0),
                    scrolly = Math.max(0, _w.pageYOffset || _d.scrollTop || _b.scrollTop || 0) - (_d.clientTop || 0);
                return {
                    width: width,
                    height: height,
                    ratio: width / height,
                    centerx: width / 2,
                    centery: height / 2,
                    scrollx: scrollx,
                    scrolly: scrolly
                };
            };
            var mouseInfo = function (e) {
                var screen = screenInfo(e),
                    mousex = e ? Math.max(0, e.pageX || e.clientX || 0) : 0,
                    mousey = e ? Math.max(0, e.pageY || e.clientY || 0) : 0;
                return {
                    mousex: mousex,
                    mousey: mousey,
                    centerx: mousex - screen.width / 2,
                    centery: mousey - screen.height / 2
                };
            };
            //点
            var Point = function (x, y) {
                this.x = 0;
                this.y = 0;
                this.set(x, y);
            };
            //点运算
            Point.prototype = {
                constructor: Point,
                set: function (x, y) {
                    this.x = x || 0; this.y = y || 0;
                },
                copy: function (point) {
                    this.x = point.x || 0; this.y = point.y || 0; return this;
                },
                multiply: function (x, y) {
                    this.x *= x || 1; this.y *= y || 1; return this;
                },
                divide: function (x, y) {
                    this.x /= x || 1; this.y /= y || 1; return this;
                },
                add: function (x, y) {
                    this.x += x || 0; this.y += y || 0; return this;
                },
                subtract: function (x, y) {
                    this.x -= x || 0; this.y -= y || 0; return this;
                },
                clampX: function (min, max) {
                    this.x = Math.max(min, Math.min(this.x, max)); return this;
                },
                clampY: function (min, max) {
                    this.y = Math.max(min, Math.min(this.y, max)); return this;
                },
                flipX: function () {
                    this.x *= -1; return this;
                },
                flipY: function () {
                    this.y *= -1; return this;
                }
            };
            //丝带画板
            var Factory = function (options) {
                this._canvas = null;
                this._context = null;
                this._sto = null;
                this._width = 0;
                this._height = 0;
                this._scroll = 0;
                this._ribbons = [];
                this._options = {
                    id: "bgCanvas",//画板Id
                    backgroundColor: "#1f1f1f",//画板背景
                    colorSaturation: "80%",//纯度
                    colorBrightness: "60%",//亮度
                    colorAlpha: 0.65,//透明度
                    colorCycleSpeed: 6,//丝带不同块之间的色彩变化量
                    verticalPosition: "center",//丝带相对于屏幕的初始位置:top/min 屏幕最上方,middle|center 中间,bottom|max 屏幕最下面
                    horizontalSpeed: 200,//丝带水平方向移动速度参数(会乘以一个随机值)
                    ribbonCount: 3,//同一时间丝带总条数
                    strokeSize: 0,//公共边路径样式
                    parallaxAmount: -0.5,//滚动偏移参数,-1表示不偏移,0表示基于丝带只出现在页面最上面
                    animateSections: true//丝带块是否偏移,显得有动感
                };
                this._onDraw = this._onDraw.bind(this);
                this._onResize = this._onResize.bind(this);
                this._onScroll = this._onScroll.bind(this);
                this.setOptions(options);
                this.init();
            };
            Factory.prototype = {
                constructor: Factory,
                setOptions: function (options) {
                    if (typeof options === "object") {
                        for (var key in options) {
                            if (options.hasOwnProperty(key)) {
                                this._options[key] = options[key];
                            }
                        }
                    }
                },
                //初始化
                init: function () {
                    //初始化画板
                    try {
                        this._canvas = document.createElement("canvas");
                        this._canvas.style["display"] = "block";
                        this._canvas.style["position"] = "fixed";
                        this._canvas.style["margin"] = "0";
                        this._canvas.style["padding"] = "0";
                        this._canvas.style["border"] = "0";
                        this._canvas.style["outline"] = "0";
                        this._canvas.style["left"] = "0";
                        this._canvas.style["top"] = "0";
                        this._canvas.style["width"] = "100%";
                        this._canvas.style["height"] = "100%";
                        this._canvas.style["z-index"] = "-1";
                        this._canvas.style["background-color"] = this._options.backgroundColor;
                        this._canvas.id = this._options.id;
                        this._onResize();
                        this._context = this._canvas.getContext("2d");
                        this._context.clearRect(0, 0, this._width, this._height);
                        this._context.globalAlpha = this._options.colorAlpha;
                        window.addEventListener("resize", this._onResize);
                        window.addEventListener("scroll", this._onScroll);
                        document.body.appendChild(this._canvas);
                    }
                    catch (e) {
                        console.warn("Canvas Context Error: " + e.toString());
                        return;
                    }
                    //开始绘画
                    this._onDraw();
                },
                //生成一条丝带
                addRibbon: function () {
                    var dir = Math.round(random(1, 9)) > 5 ? "right" : "left",//丝带延伸方向
                        stop = 1000,
                        hide = 200,
                        min = 0 - hide,
                        max = this._width + hide,
                        movex = 0,
                        movey = 0,
                        startx = dir === "right" ? min : max,//起始点x左边
                        starty = Math.round(random(0, this._height));//起始点y左边
                    //丝带生成的位置
                    if (/^(top|min)$/i.test(this._options.verticalPosition)) {//最上方
                        starty = 0 + hide;
                    } else if (/^(middle|center)$/i.test(this._options.verticalPosition)) {//中间
                        starty = this._height / 2;
                    } else if (/^(bottom|max)$/i.test(this._options.verticalPosition)) {//最下方
                        starty = this._height - hide;
                    }
                    if (this._options.parallaxAmount !== 0) {
                        starty += this._scroll;//加上滚动
                    }
                    var ribbon = [],
                        point1 = new Point(startx, starty),
                        point2 = new Point(startx, starty),
                        point3 = null,
                        color = Math.round(random(0, 360)),
                        delay = 0;
                    //从起始位置开始生成一条丝带
                    //丝带每个分部都是一个三角形,三点确定一个三角形,相邻三角形有一条公共边
                    while (true) {
                        if (stop <= 0) break;
                        stop--;
                        movex = Math.round((Math.random() * 1 - 0.2) * this._options.horizontalSpeed);
                        movey = Math.round((Math.random() * 1 - 0.5) * (this._height * 0.25));
                        point3 = new Point();
                        point3.copy(point2);
                        if (dir === "right") {
                            point3.add(movex, movey);
                            if (point2.x >= max) break;
                        } else if (dir === "left") {
                            point3.subtract(movex, movey);
                            if (point2.x <= min) break;
                        }
                        ribbon.push({
                            //三点
                            point1: new Point(point1.x, point1.y),
                            point2: new Point(point2.x, point2.y),
                            point3: point3,
                            color: color,//丝带颜色
                            delay: delay,//延迟消失
                            dir: dir,//方向
                            alpha: 0,//透明度
                            phase: 0 //随机位移有关参数
                        });
                        //公共边
                        point1.copy(point2);
                        point2.copy(point3);
                        delay += 4;
                        color += this._options.colorCycleSpeed;
                    }
                    this._ribbons.push(ribbon);
                },
                //绘制一个三角形方块
                _drawRibbonSection: function (section) {
                    if (section) {
                        if (section.phase >= 1 && section.alpha <= 0) {
                            return true;
                        }
                        if (section.delay <= 0) {
                            section.phase += 0.02;
                            section.alpha = Math.sin(section.phase) * 1;
                            section.alpha = section.alpha <= 0 ? 0 : section.alpha;
                            section.alpha = section.alpha >= 1 ? 1 : section.alpha;
                            if (this._options.animateSections) {
                                var mod = Math.sin(1 + section.phase * Math.PI / 2) * 0.1;
                                if (section.dir === "right") {
                                    section.point1.add(mod, 0);
                                    section.point2.add(mod, 0);
                                    section.point3.add(mod, 0);
                                } else {
                                    section.point1.subtract(mod, 0);
                                    section.point2.subtract(mod, 0);
                                    section.point3.subtract(mod, 0);
                                }
                                section.point1.add(0, mod);
                                section.point2.add(0, mod);
                                section.point3.add(0, mod);
                            }
                        } else {
                            section.delay -= 0.5;
                        }
                        var s = this._options.colorSaturation,
                            l = this._options.colorBrightness,
                            c = "hsla(" + section.color + ", " + s + ", " + l + ", " + section.alpha + " )";
                        //绘制一个方块
                        this._context.save();
                        if (this._options.parallaxAmount !== 0) {
                            this._context.translate(0, this._scroll * this._options.parallaxAmount);
                        }
                        this._context.beginPath();
                        this._context.moveTo(section.point1.x, section.point1.y);
                        this._context.lineTo(section.point2.x, section.point2.y);
                        this._context.lineTo(section.point3.x, section.point3.y);
                        this._context.fillStyle = c;
                        this._context.fill();
                        if (this._options.strokeSize > 0) {
                            this._context.lineWidth = this._options.strokeSize;
                            this._context.strokeStyle = c;
                            this._context.lineCap = "round";
                            this._context.stroke();
                        }
                        this._context.restore();
                    }
                    return false;
                },
                //绘制丝带
                _onDraw: function () {
                    //清空已经绘制过的丝带
                    for (var i = 0, t = this._ribbons.length; i < t; ++i) {
                        if (!this._ribbons[i]) {
                            this._ribbons.splice(i, 1);
                        }
                    }
                    this._context.clearRect(0, 0, this._width, this._height);//清空画板
                    for (var a = 0; a < this._ribbons.length; ++a) {
                        var ribbon = this._ribbons[a],
                            numSections = ribbon ? ribbon.length : 0,
                            numDone = 0;
                        //绘制整条丝带
                        for (var b = 0; b < numSections; ++b) {
                            if (this._drawRibbonSection(ribbon[b])) {
                                numDone++;
                            }
                        }
                        //丝带已经全部飘过屏幕,设置为null,函数前面会自动清理
                        if (numDone >= numSections) {
                            this._ribbons[a] = null;
                        }
                    }
                    //随机生成一条丝带
                    if (this._ribbons.length < this._options.ribbonCount && Math.random() > 0.99) {
                        this.addRibbon();
                    }
                    //调度交给系统,当需要刷新画板时调用指定的回调函数,用于提高性能
                    requestAnimationFrame(this._onDraw);
                },
                //重新设置窗体大小时需要获取窗体大小
                _onResize: function (e) {
                    var screen = screenInfo(e);
                    this._width = screen.width;
                    this._height = screen.height;
                    if (this._canvas) {
                        this._canvas.width = this._width;
                        this._canvas.height = this._height;
                        if (this._context) {
                            this._context.globalAlpha = this._options.colorAlpha;
                        }
                    }
                },
                //滚动时获取滚动距离
                _onScroll: function (e) {
                    var screen = screenInfo(e);
                    this._scroll = screen.scrolly;
                }
            }; return Factory;
        });
    //初始化并绘制
    new Ribbons({
        ribbonCount: 5,
        parallaxAmount: -0.99
    });
注意,在代码的最后面有丝带的初始化
//初始化并绘制
new Ribbons({
ribbonCount: 5,
parallaxAmount: -0.99
});
里面可以传的参数有
    options = {
        id: "bgCanvas",//画板Id
        backgroundColor: "#1f1f1f",//画板背景
        colorSaturation: "80%",//纯度
        colorBrightness: "60%",//亮度
        colorAlpha: 0.65,//透明度
        colorCycleSpeed: 6,//丝带不同块之间的色彩变化量
        verticalPosition: "center",//丝带相对于屏幕的初始位置:top/min 屏幕最上方,middle|center 中间,bottom|max 屏幕最下面
        horizontalSpeed: 200,//丝带水平方向移动速度参数(会乘以一个随机值)
        ribbonCount: 3,//同一时间丝带总条数
        strokeSize: 0,//公共边路径样式
        parallaxAmount: -0.5,//滚动偏移参数,-1表示不偏移,0表示基于丝带只出现在页面最上面
        animateSections: true//丝带块是否偏移,显得有动感
    };
另外这个部分初始化代码可以提取出来放到其他地方去初始化,比如window的onload里面,这里直接这么写是为了将上面的代码封装到一个js文件中,然后直接引用js文件即可,但是注意一下,这里最好在body的最后面引用,否则可能会导致一些页面加载不全导致的问题,如新建一个html文件:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Ribbons</title>
</head>
<body>
<!--这里最好在body的最后面引用js文件-->
<!--本地-->
<script src="ribbons.js"></script>
<!--远程-->
<!--<script src="https://blog-static.cnblogs.com/files/shanfeng1000/ribbons.js"></script>-->
</body>
</html>
浏览器打开html文件
  
   
很漂亮的一个背景控件——ribbons.js的更多相关文章
- 很漂亮的Wince开发控件库Beemobile简介【转】
		
https://blog.csdn.net/xiaoyong_net/article/details/80467653 官网地址:http://beemobile4.net/products/ipac ...
 - swing实现QQ登录界面1.0( 实现了同一张图片只加载一次)、(以及实现简单的布局面板添加背景图片控件的标签控件和添加一个关闭按钮控件)
		
swing实现QQ登录界面1.0( 实现了同一张图片只加载一次).(以及实现简单的布局面板添加背景图片控件的标签控件和添加一个关闭按钮控件) 代码思路分析: 1.(同一张图片仅仅需要加载一次就够了,下 ...
 - 如何设计一个 iOS 控件?(iOS 控件完全解析) (转)
		
前言 一个控件从外在特征来说,主要是封装这几点: 交互方式 显示样式 数据使用 对外在特征的封装,能让我们在多种环境下达到 PM 对产品的要求,并且提到代码复用率,使维护工作保持在一个相对较小的范围内 ...
 - 如何设计一个 iOS 控件?(iOS 控件完全解析)
		
前言 一个控件从外在特征来说,主要是封装这几点: 交互方式 显示样式 数据使用 对外在特征的封装,能让我们在多种环境下达到 PM 对产品的要求,并且提到代码复用率,使维护工作保持在一个相对较小的范围内 ...
 - 设计一个 iOS 控件
		
转载自:http://blog.csdn.net/zhangao0086/article/details/45622875 代码的等级:可编译.可运行.可测试.可读.可维护.可复用 前言 一个控件从外 ...
 - Android 一个日历控件的实现代码
		
转载 2017-05-19 作者:Othershe 我要评论 本篇文章主要介绍了Android 一个日历控件的实现代码,小编觉得挺不错的,现在分享给大家,也给大家做个参考.一起跟随小编过来看 ...
 - Qt编写自定义控件26-平铺背景控件
		
一.前言 平铺背景控件,主要的应用场景是作为画布出现,黑白相间的背景图,然后上面可以放置图片图形等,使得看起来更美观,比如PS软件新建图层以后的背景,FireWorks软件新建画布以后的透明背景,IC ...
 - 使用 ViewPager 和 RadioGroup 封装的一个导航控件
		
import android.animation.ObjectAnimator; import android.content.Context; import android.graphics.dra ...
 - appium+python:自己写的一个滑动控件的方式
		
#调用方式roll_ele("ID","ele_id","7","up",3)#将控件分为7格,从底部倒数第二格向上滑动 ...
 
随机推荐
- PhoneGap本地将html打包成安卓App
			
PhoneGap的在线打包有大小限制,超过30M的包无法在线打包.当然,可以把包里面的图片.声音文件去掉,然后打包.下载以后,解包,重新打包并签名.蛮麻烦的. 本地打包的简单方法如下: 下载安装Jav ...
 - JAVA序列化浅析
			
java.io.Serializable浅析 Java API中java.io.Serializable接口源码: 1 public interface Serializable { 2 } 类通过实 ...
 - String直接赋值与使用new String的区别
			
在研究String直接赋值与new String的区别之前我们需要先了解java中的字符串常量池的概念 字符串常量池 String类是我们平常项目中使用频率非常高的一种对象类型,jvm为了提升性能和减 ...
 - 【Java基础】transient关键字
			
1. transient的作用及使用方法 我们都知道一个对象只要实现了Serilizable接口,这个对象就可以被序列化,java的这种序列化模式为开发者提供了很多便利,我们可以不必关系具体序列化的过 ...
 - mybatis的dao层和service层的编码设计的配置
			
/** 书写pojo类------>dao接口------>resources下建立同路径的dao.xml------>配置applicationContext.xml文件 **/ ...
 - 什么是maven(二)
			
转自博主--一杯凉茶 maven项目构建ssh工程(父工程与子模块的拆分与聚合) 前一节我们明白了maven是个什么玩意,这一节就来讲讲他的一个重要的应用场景,也就是通过maven将一个ssh项目 ...
 - python基础 (三)
			
成员运算 判断某个个体在不在某个群体里,关键词:in(在),not in(不在)例如: 特殊的,如果是字典中,因为字典的V值是隐藏的,能查看的只有V,所以无法判断V值,只能判断K值. 身份运算 用于判 ...
 - glViewport()函数和glOrtho()函数的理解
			
glViewport()函数和glOrtho()函数的理解 OpenGL中有两个比较重要的投影变换函数,glViewport和glOrtho. glOrtho是创建一个正交平行的视景体. 一般 ...
 - cron 获取下次运行时间(基于 C# + Quartz.NET)
			
代码 Quartz 的 cron 支持秒,导致一些 cron 库无法准确的获得下次执行时间,这里使用 Quartz.Net 自带的方法来获取下次执行时间. //引用 Quartz CronExpres ...
 - CF125A Measuring Lengths in Baden 题解
			
Content 在 Baden,一英寸等于 \(3\) 厘米,一英尺等于 \(12\) 英寸. 现在有一个 \(n\) 厘米的物体,求在 Baden,它是几英尺又几英寸. 数据范围:\(1\leqsl ...