效果图如下:

背景乱码动态效果

代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>背景乱码动态效果</title>
</head>
<body>
<canvas id="animateCode"></canvas>
<script>
    var c = document.getElementById("animateCode");
    //目前只能为2d
    var ctx = c.getContext("2d");
    //全屏
    c.height = window.innerHeight;
    c.width = window.innerWidth;
    //文字 数字&字母
    var txt = "0123456789abcdefghijklmnopqrstuvwxyz" +
        "ABCDEFGHIJKLMNOPQRSTUVWXYZαβγδεζηθικλμνξοπρστυφχψω" +
        "クサシセソチッテンナフヘマムメャヮ~<>/?'[]{}-+=)(*&^%#@αβγδεζηθικλμνξοπρστυφχψω";
    //转为数组
    txt = txt.split("");
    //字体大小
    var font_size = 12;
    //用于计算输出文字时坐标,所以长度即为列数
    var columns = c.width / font_size;
    //an array of drops - one per column
    var drops = [];
    //x below is the x coordinate
    //1 = y co-ordinate of the drop(same for every drop initially)
    for (var x = 0; x < columns; x++)
        drops[x] = 1;
    //输出文字
    function draw() {
        //Black BG for the canvas
        //translucent BG to show trail
        //让背景逐渐由透明到不透明
        ctx.fillStyle = "rgba(0, 0, 0, 0.1)";
        ctx.fillRect(0, 0, c.width, c.height);
        var my_gradient = ctx.createLinearGradient(0, 0, c.width, 0);
        my_gradient.addColorStop(0, "white");
        my_gradient.addColorStop(0.15, "green");
        my_gradient.addColorStop(0.85, "green");
        my_gradient.addColorStop(1, "white");
        ctx.fillStyle = my_gradient;
        // ctx.fillStyle = "rgba(0, 255, 0, 1)"; //文字颜色 //green text
        ctx.font = font_size + "px arial";
        //looping over drops
        //逐行输出文字
        for (var i = 0; i < drops.length; i++) {
            //a random chinese character to print
            //随机取要输出的文字
            var text = txt[Math.floor(Math.random() * txt.length)];
            //x = i*font_size, y = value of drops[i]*font_size
            //输出文字,注意坐标的计算
            ctx.fillText(text, i * font_size, drops[i] * font_size);
            //sending the drop back to the top randomly after it has crossed the screen
            //adding a randomness to the reset to make the drops scattered on the Y axis
            //如果绘满一屏或随机数大于0.97(此数可自行调整,效果会不同)
            if (drops[i] * font_size > c.height && Math.random() > 0.99)
                drops[i] = 0;
            //incrementing Y coordinate
            //用于Y轴坐标增加
            drops[i]++;
        }
    }
    //时间间隔
    setInterval(draw, 65);
</script>
</body>
</html>

相关文章: