JavaScript特效代码收集

页面“线条”效果

引自:http://www.sojson.com/blog/127.html

<!-- 这个script 引入得放到<body> 里,放到header 里,会报错。并且不依赖其他js 插件。 --!>
<!-- 参数解释 count  :线条数量;zindex :层级;opacity:透明度;color   :线条颜色,最好用RGB颜色 --!>
<script count="200" zindex="-2" opacity="0.5" color="47,135,193" type="text/javascript"> 
! function() {
    //封装方法,压缩之后减少文件大小
    function get_attribute(node, attr, default_value) {
        return node.getAttribute(attr) || default_value;
    }
    //封装方法,压缩之后减少文件大小
    function get_by_tagname(name) {
        return document.getElementsByTagName(name);
    }
    //获取配置参数
    function get_config_option() {
        var scripts = get_by_tagname("script"),
            script_len = scripts.length,
            script = scripts[script_len - 1]; //当前加载的script
        return {
            l: script_len, //长度,用于生成id用
            z: get_attribute(script, "zIndex", -1), //z-index
            o: get_attribute(script, "opacity", 0.5), //opacity
            c: get_attribute(script, "color", "0,0,0"), //color
            n: get_attribute(script, "count", 99) //count
        };
    }
    //设置canvas的高宽
    function set_canvas_size() {
        canvas_width = the_canvas.width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth, 
        canvas_height = the_canvas.height = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
    }

    //绘制过程
    function draw_canvas() {
        context.clearRect(0, 0, canvas_width, canvas_height);
        //随机的线条和当前位置联合数组
        var all_array = [current_point].concat(random_lines);
        var e, i, d, x_dist, y_dist, dist; //临时节点
        //遍历处理每一个点
        random_lines.forEach(function(r) {
            r.x += r.xa, 
            r.y += r.ya, //移动
            r.xa *= r.x > canvas_width || r.x < 0 ? -1 : 1, 
            r.ya *= r.y > canvas_height || r.y < 0 ? -1 : 1, //碰到边界,反向反弹
            context.fillRect(r.x - 0.5, r.y - 0.5, 1, 1); //绘制一个宽高为1的点
            for (i = 0; i < all_array.length; i++) {
                e = all_array[i];
                //不是当前点
                if (r !== e && null !== e.x && null !== e.y) {
                        x_dist = r.x - e.x, //x轴距离 l
                        y_dist = r.y - e.y, //y轴距离 n
                        dist = x_dist * x_dist + y_dist * y_dist; //总距离, m
                    dist < e.max && (e === current_point && dist >= e.max / 2 && (r.x -= 0.03 * x_dist, r.y -= 0.03 * y_dist), //靠近的时候加速
                        d = (e.max - dist) / e.max, 
                        context.beginPath(), 
                        context.lineWidth = d / 2, 
                        context.strokeStyle = "rgba(" + config.c + "," + (d + 0.2) + ")", 
                        context.moveTo(r.x, r.y), 
                        context.lineTo(e.x, e.y), 
                        context.stroke());
                }
            }
            all_array.splice(all_array.indexOf(r), 1);

        }), frame_func(draw_canvas);
    }
    //创建画布,并添加到body中
    var the_canvas = document.createElement("canvas"), //画布
        config = get_config_option(), //配置
        canvas_id = "c_n" + config.l, //canvas id
        context = the_canvas.getContext("2d"), canvas_width, canvas_height, 
        frame_func = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function(func) {
            window.setTimeout(func, 1000 / 45);
        }, random = Math.random, 
        current_point = {
            x: null, //当前鼠标x
            y: null, //当前鼠标y
            max: 20000
        };
    the_canvas.id = canvas_id;
    the_canvas.style.cssText = "position:fixed;top:0;left:0;z-index:" + config.z + ";opacity:" + config.o;
    get_by_tagname("body")[0].appendChild(the_canvas);
    //初始化画布大小

    set_canvas_size(), window.onresize = set_canvas_size;
    //当时鼠标位置存储,离开的时候,释放当前位置信息
    window.onmousemove = function(e) {
        e = e || window.event, current_point.x = e.clientX, current_point.y = e.clientY;
    }, window.onmouseout = function() {
        current_point.x = null, current_point.y = null;
    };
    //随机生成config.n条线位置信息
    for (var random_lines = [], i = 0; config.n > i; i++) {
        var x = random() * canvas_width, //随机位置
            y = random() * canvas_height,
            xa = 2 * random() - 1, //随机运动方向
            ya = 2 * random() - 1;
        random_lines.push({
            x: x,
            y: y,
            xa: xa,
            ya: ya,
            max: 6000 //沾附距离
        });
    }
    //0.1秒后绘制
    setTimeout(function() {
        draw_canvas();
    }, 100);
}();
</script>

正计时

引自:http://meihuaqizi.com/

<!DOCTYPE html>
<html>
<head>
    <meta charset = "utf-8">
    <meta property="wb:webmaster" content="9a2d177f81696c94" />
    <!-- 该文件需要下载到本地 --!>
    <script type="text/javascript" src = "http://meihuaqizi.com/jquery.1.4.2.js"></script>
    <!-- 该文件需要下载到本地 --!>
    <script type="text/javascript" src = "http://meihuaqizi.com/animateBackground-plugin.js"></script>
    <!-- 此处的属性startDate指定了正计时开始的时间 --!>
    <script type="text/javascript" startDate="1992/04/09 19:54:00" >
        $(function(){
            getDate();
            setInterval('getDate()', 1000);//每隔1秒执行一次
        });

            var days,minutes,secondes
            var scripts = document.getElementsByTagName("script"),
            script_len = scripts.length,
            script = scripts[script_len - 1]; //当前加载的script
            function getDate(){
                var birthday = new Date(script.getAttribute("startDate"));
                var date = new Date();
                var date3 = date.getTime() - birthday.getTime();
                // document.write(date3);
                //计算出相差天数
                days=Math.floor(date3/(24*3600*1000));
                //计算出小时数
                var leave1=date3%(24*3600*1000);    //计算天数后剩余的毫秒数
                var hours=Math.floor(leave1/(3600*1000));
                //计算相差分钟数
                var leave2=leave1%(3600*1000);        //计算小时数后剩余的毫秒数
                minutes=Math.floor(leave2/(60*1000));
                //计算相差秒数
                var leave3=leave2%(60*1000);      //计算分钟数后剩余的毫秒数
                //此处原代码有bug,应该仍然下取整
                seconds=Math.floor(leave3/1000);
                // document.write(days+"天"+hours+"时"+minutes+"分"+seconds+"秒  ")
                hours = fix(hours,2);
                minutes = fix(minutes,2);
                seconds = fix(seconds,2);
                show_num("#day",days);
                show_num("#hour",hours);
                show_num("#minute",minutes);
                show_num("#second",seconds);
            }

            function fix(num, length) {
                return ('' + num).length < length ? ((new Array(length + 1)).join('0') + num).slice(-length) : '' + num;
            }

            function show_num(elem,n){
                var it = $(elem+" i"); 
                var len = String(n).length; 
                for(var i=0;i<len;i++){ 
                    if(it.length<=i){ 
                        $(elem).append("<i></i>"); 
                } 
                    var num=String(n).charAt(i); 
                    var y = -parseInt(num)*30; //y轴位置 
                    var obj = $(elem+" i").eq(i); 
                    obj.animate({ //滚动动画 
                        backgroundPosition :'(0 '+String(y)+'px)'  
                        }, 'slow','swing',function(){} 
                    ); 
                }
            }
    </script>
    <!-- 该处使用了图片资源文件,该文件需要下载到本地 --!>
    <style type="text/css">
        #div{width:500px; height:40px; line-height:40px; margin:200px auto 20px auto; font-size:20px}
        #div #day{ display:inline-block; line-height:13px; margin:2px 4px 0 4px;}
        #div #hour{ display:inline-block; line-height:13px; margin:2px 4px 0 4px;}
        #div #minute{ display:inline-block; line-height:13px; margin:2px 4px 0 4px;}
        #div #second{ display:inline-block; line-height:13px; margin:2px 4px 0 4px;}
        #div #day i{width:15px;height:23px; display:inline-block; background: url(http://meihuaqizi.com/number.png) no-repeat; background-position:0 0; text-indent:-999em}
        #div #hour i{width:15px;height:23px; display:inline-block; background: url(http://meihuaqizi.com/number.png) no-repeat; background-position:0 0; text-indent:-999em}
        #div #minute i{width:15px;height:23px; display:inline-block; background: url(http://meihuaqizi.com/number.png) no-repeat; background-position:0 0; text-indent:-999em}
        #div #second i{width:15px;height:23px; display:inline-block; background: url(http://meihuaqizi.com/number.png) no-repeat; background-position:0 0; text-indent:-999em}
    </style>
</head>
<body>
<div id = "div"> 
    <span id = "day"></span>Days
    <span id = "hour"></span>Hours
    <span id = "minute"></span>Minutes
    <span id = "second"></span>Seconds
</div> 
</body>
</html>

字符串进化

引自:https://huzidaha.github.io/home/

<!-- 变化字符的显示标签必须命名id为"StrEvolution",也可以是<span/>, <a/>等标签;但其内文本只支持英文字母和逗号,句号 --!>
<h3 id="StrEvolution"> This is a funny action. </h3>

<script>
/******/ (function(modules) { // webpackBootstrap
/******/    // The module cache
/******/    var installedModules = {};

/******/    // The require function
/******/    function __webpack_require__(moduleId) {

/******/        // Check if module is in cache
/******/        if(installedModules[moduleId])
/******/            return installedModules[moduleId].exports;

/******/        // Create a new module (and put it into the cache)
/******/        var module = installedModules[moduleId] = {
/******/            exports: {},
/******/            id: moduleId,
/******/            loaded: false
/******/        };

/******/        // Execute the module function
/******/        modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);

/******/        // Flag the module as loaded
/******/        module.loaded = true;

/******/        // Return the exports of the module
/******/        return module.exports;
/******/    }


/******/    // expose the modules object (__webpack_modules__)
/******/    __webpack_require__.m = modules;

/******/    // expose the module cache
/******/    __webpack_require__.c = installedModules;

/******/    // __webpack_public_path__
/******/    __webpack_require__.p = "";

/******/    // Load entry module and return exports
/******/    return __webpack_require__(0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ function(module, exports, __webpack_require__) {

    'use strict';

    var _gen = __webpack_require__(1);

    var _gen2 = _interopRequireDefault(_gen);

    function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

    var isRunning = false;

    var init = function init() {
      redirectPosts();
      listen();
      play();
    };

    function redirectPosts() {
      var capture = window.location.search.match(/\?post=(\d+)/);
      var postid = capture ? capture[1] : null;
      if (postid) {
        window.location.href = 'https://github.com/livoras/blog/issues/' + postid;
      }
    }

    function listen() {
      document.getElementById('StrEvolution').addEventListener('click', function () {
        if (isRunning) return;
        play();
      });
    }

    function play() {
      var head = document.getElementById('StrEvolution');
      var headTxt = head.innerText
      var history = (0, _gen2.default)(headTxt).history;
      isRunning = true;
      var i = 0;
      history.forEach(function (text, i) {
        setTimeout(function () {
          head.innerText = text;
          if (++i === history.length) isRunning = false;
        }, i * 30);
      });
    }

    init();

/***/ },
/* 1 */
/***/ function(module, exports, __webpack_require__) {

    'use strict';

    /**
     * Using Genetic Algorithm to generate lots of random strings
     * and make them evolve towards the target string.
     *
     */

    var Genea = __webpack_require__(2);
    var alphabetArr = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ., '.split('');
    var alphabet = function () {
      var alphabet = {};
      alphabetArr.forEach(function (ch, i) {
        alphabet[ch] = i;
      });
      return alphabet;
    }();

    function getTargetStr(targetStr) {
      var binaryStr = '';
      for (var i = 0, len = targetStr.length; i < len; i++) {
        var ch = targetStr[i];
        var chIndex = alphabet[ch];
        binaryStr += paddingWith0(Number(chIndex).toString(2));
      }
      return binaryStr;
    }

    function paddingWith0(num) {
      while (num.length < 6) {
        num = '0' + num;
      }
      return num;
    }

    function run(str) {
      var tar = getTargetStr(str);
      var ga = new Genea({
        geneLength: tar.length,
        mutateProbability: 0.5,
        doneFitness: 1,
        populationSize: 20,
        generationsSize: 400,
        getFitness: function getFitness(gene) {
          var count = 0;
          for (var i = 0, len = gene.length; i < len; i++) {
            if (gene[i] === tar[i]) count++;
          }
          var likeness = count / tar.length;
          return likeness;
        },
        onGeneration: function onGeneration(generation, genes) {
          var max = 0,
              index = 0;
          this.fitnesses.forEach(function (fitness, i) {
            if (fitness > max) {
              max = fitness;
              index = i;
            }
          });
          this.history.push(toChars(genes[index]));
        }
      });

      ga.history = [];
      ga.start();
      return ga;
    }

    function toChars(gene) {
      var str = '';
      while (gene.length) {
        var ch = '00' + gene.substr(0, 6);
        gene = gene.substr(6);
        var chIndex = parseInt(ch, 2);
        if (chIndex >= alphabetArr.length) {
          chIndex = Math.floor(Math.random() * (alphabetArr.length - 1));
        }
        if (!alphabetArr[chIndex]) console.log(chIndex, parseInt(ch, 2));
        str += alphabetArr[chIndex];
      }
      return str;
    }

    module.exports = run;

/***/ },
/* 2 */
/***/ function(module, exports) {

    'use strict';

    var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

    function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

    var Genea = function () {
      function Genea(config) {
        _classCallCheck(this, Genea);

        this.currentGeneration = 0;
        this.populations = [];
        this.fitnesses = [];

        this.mutateProbability = config.mutateProbability || 0.5; // 0 ~ 1
        this.generationsSize = config.generationsSize || 100;
        this.populationSize = config.populationSize || 100;
        this.doneFitness = config.doneFitness || 1; // 0 ~ 1

        this.geneLength = config.geneLength;
        this.getFitness = config.getFitness;

        this.outOfGenerationsSize = config.outOfGenerationsSize || this.outOfGenerationsSize;
        this.onGeneration = config.onGeneration || this.onGeneration;
        this.done = config.done || this.done;
      }

      _createClass(Genea, [{
        key: "start",
        value: function start() {
          this.initPopulation();
          this.makeFitnesses();
          this.select();
        }
      }, {
        key: "initPopulation",
        value: function initPopulation() {
          this.currentGeneration = 1;
          this.populations = [];
          for (var i = 0, len = this.populationSize; i < len; i++) {
            var gene = getRandomGene(this.geneLength);
            this.populations.push(gene);
          }
          this.onGeneration(this.currentGeneration, this.populations);
        }
      }, {
        key: "select",
        value: function select() {
          if (this.currentGeneration >= this.generationsSize) {
            return this.outOfGenerationsSize(this.populations, this.fitnesses);
          }
          var matches = this.getMatches();
          if (matches.length > 0) return this.done(matches);
          this.generateNextGeneration();
        }
      }, {
        key: "makeFitnesses",
        value: function makeFitnesses() {
          var _this = this;

          this.fitnesses = [];
          this.totalFitness = 0;
          this.populations.forEach(function (individual, i) {
            var fitness = _this.getFitness(individual, _this.populations);
            _this.fitnesses[i] = fitness;
            _this.totalFitness += fitness;
          });
        }
      }, {
        key: "getMatches",
        value: function getMatches() {
          var _this2 = this;

          var bests = [];
          this.populations.forEach(function (individual, i) {
            var fitness = _this2.fitnesses[i];
            if (fitness >= _this2.doneFitness) {
              bests.push({
                gene: individual,
                fitness: fitness,
                pos: i
              });
            }
          });
          return bests;
        }
      }, {
        key: "generateNextGeneration",
        value: function generateNextGeneration() {
          this.currentGeneration++;
          var oldPopulations = this.populations;
          var newPopulations = [];
          for (var i = 0, len = oldPopulations.length; i < len; i++) {
            var father = this.rotate();
            var mother = this.rotate();
            var child = this.crossOver(father, mother);
            child = this.mutate(child);
            newPopulations.push(child);
          }
          this.populations = newPopulations;
          this.makeFitnesses();
          this.onGeneration(this.currentGeneration, this.populations);
          this.select();
        }
      }, {
        key: "crossOver",
        value: function crossOver(father, mother) {
          var pos = Math.floor(father.length * Math.random());
          var child1 = father.substring(0, pos) + mother.substring(pos);
          var child2 = mother.substring(0, pos) + father.substring(pos);
          return this.getFitness(child1) > this.getFitness(child2) ? child1 : child2;
        }
      }, {
        key: "mutate",
        value: function mutate(child) {
          var mutateProbability = Math.random();
          if (mutateProbability < this.mutateProbability) return child;
          var pos = Math.floor(Math.random() * this.geneLength);
          var arr = child.split("");
          arr[pos] = +child[pos] ^ 1;
          return arr.join("");
        }
      }, {
        key: "rotate",
        value: function rotate() {
          var pos = Math.random(); // let's roll!
          var soFar = 0;
          for (var i = 0, len = this.fitnesses.length; i < len; i++) {
            var fitness = this.fitnesses[i];
            soFar += fitness;
            if (soFar / this.totalFitness >= pos) {
              return this.populations[i];
            }
          }
        }
      }, {
        key: "done",
        value: function done() {}
      }, {
        key: "onGeneration",
        value: function onGeneration() {}
      }, {
        key: "outOfGenerationsSize",
        value: function outOfGenerationsSize() {}
      }]);

      return Genea;
    }();

    function getRandomGene(len) {
      var gene = "";
      for (var i = 0; i < len; i++) {
        gene += Math.floor(Math.random() * 100) % 2 === 0 ? "1" : "0";
      }
      return gene;
    }

    module.exports = Genea;

/***/ }
/******/ ]);
</script>

旋转地球仪

引自:http://www.gbtags.com/gb/rtreplayerpreview/369.htm

<!-- 这段javascript代码必须顶开头写 --!>
<script>
eval(z='p="<"+"pre>"/*  ############   */;for(y in n="zw24l6k\
4e3t4jnt4qj24xh2 x/* ##############      */42kty24wrt413n243n\
9h243pdxt41csb yz/*#################    * */43iyb6k43pk7243nm\
r24".split(4)){/* ###########*            # */for(a in t=pars\
eInt(n[y],36)+/**#############           ### */(e=x=r=[]))for\
(r=!r,i=0;t[a/*  *############            ### */]>i;i+=.05)wi\
th(Math)x-= /*   #############            *#*  */.05,0>cos(o=\
new Date/1e3/*   #######*                 *### */+x/PI)&&(e[~\
~(32*sin(o)*/*      ####*              ####### */sin(.5+y/7))\
+60] =-~ r);/*          *####*        *####### */for(x=0;122>\
x;)p+="   *#"/*          ########*       *### */[e[x++]+e[x++\
]]||(S=("eval"/*         ############*     # */+"(z=\'"+z.spl\
it(B = "\\\\")./*        *#######         # */join(B+B).split\
(Q="\'").join(B+Q/*       ######*       * */)+Q+")//m1k")[x/2\
+61*y-1]).fontcolor/*     *##*         * */(/\\w/.test(S)&&"#\
03B");document.body.innerHTML=p+=B+"\\n"}setTimeout(z)')//m1k\
</script>

猜你喜欢

转载自blog.csdn.net/zhiyuan411/article/details/56667876