Melody主题的背景代码雨特效


一个多月前折腾完的melody主题上的背景代码雨特效,今天终于良心发现来填坑了)

顺便吐槽一句melody相关的资料真的好少,完全靠自己看主题源码+和其他主题对比来摸索,这大概就是开荒的痛并快乐着吧T.T。(形成用户生态是有多重要.jpg

参考文章(Hexo 博客优化之博客美化系列(持续更新))里的是以Material主题为例,本文以Melody主题为例。

背景效果如图(https://c10udlnk.top/):

以下步骤均以博客文件夹为当前目录。

js文件创建

.\node_modules\hexo-theme-melody\source\js下新建一个DigitalRain.js(跟参考文章的不一样,原文章的特效定位有问题,所以这里有魔改):

window.onload = function(){
    var canvas = document.createElement('canvas'),
    context = canvas.getContext('2d'),
    pr = window.devicePixelRatio || 1,
    width = window.innerWidth,
    height = window.innerHeight
    canvas.width = width * pr
    canvas.height = height * pr
    context.scale(pr, pr)
    context.globalAlpha = 0.8
    canvas.style.cssText =
    'opacity:0.8;position:fixed;top:0;left:0;z-index:-1;width:100%;height:100%;pointer-events:none;'
    // create canvas
    document.getElementsByTagName('body')[0].appendChild(canvas);
    // var canvas = document.getElementById("mycanvas");
    // //获取画布的上下文
    // var context =canvas.getContext("2d");
    // var s = window.screen;
    // var W = canvas.width = s.width;
    // var H = canvas.height;
    //获取浏览器屏幕的宽度和高度
    //var W = window.innerWidth;
    //var H = window.innerHeight;
    //设置canvas的宽度和高度
    // canvas.width = W;
    // canvas.height = H;
    //每个文字的字体大小
    var fontSize = 12;
    //计算列
    var colunms = Math.floor(canvas.width /fontSize);  
    //记录每列文字的y轴坐标
    var drops = [];
    //给每一个文字初始化一个起始点的位置
    for(var i=0;i= canvas.height && Math.random() > 0.99){
                drops[i] = 0;
            }
            drops[i]++;
        }
    };
    function randColor(){//随机颜色
        var r = Math.floor(Math.random() * 256);
        var g = Math.floor(Math.random() * 256);
        var b = Math.floor(Math.random() * 256);
        return "rgb("+r+","+g+","+b+")";
    }
    draw();
    setInterval(draw,35);
};

更改pug文件

.\node_modules\hexo-theme-melody\layout\includes\additional-js.pug里最开头添加一句:include ./third-party/DigitalRain.pug

然后在.\node_modules\hexo-theme-melody\layout\includes\third-party下新建一个DigitalRain.pug

script(src=url_for('/js/DigitalRain.js'))

这样背景就有代码雨特效啦~