美文网首页
canvas+js实现数字雨特效

canvas+js实现数字雨特效

作者: 拾实 | 来源:发表于2018-10-30 16:16 被阅读0次

0.效果预览

数字雨.gif

1.完整代码及思路

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>数字雨</title>
    <style>
        body{
            margin: 0;
            padding: 0;
            background-color: black;
            overflow: hidden;
        }
    </style>
    <script>
        window.onload=function(){
        var drCav = document.getElementById("digitalRain");
        
        /*将画布大小设置为窗口文档显示区大小*/
        var width = window.innerWidth;
        var height = window.innerHeight;
        drCav.width = width;
        drCav.height = height;
    
        var fontsize = 16;                          //数字字体大小
        var columns = Math.ceil(width / fontsize);  //列数(向上取整)
        var dropLine = [];                          
        for (var i = 0; i < columns; i++) {
            dropLine[i] = 0;
        }
        
        /*Run*/
        if(drCav.getContext){
            var ctx = drCav.getContext("2d");
            timer = setInterval(draw, 30);
        }

        function draw() {
            ctx.fillStyle = "rgba(0, 0, 0, 0.05)";   //设置透明度,逐渐覆盖之前的数字
            ctx.fillRect(0, 0, width, height);       //填充画布
            
            ctx.fillStyle = "#00FF00";               
            ctx.font = fontsize + "px Simsun";
            for (var i = 0; i < columns; i++) {
                var figure = Math.floor(Math.random()*10);  //生成0~9的伪随机数
                
                /*绘制数字(核心部分)*/
                ctx.fillText(figure, i * fontsize, dropLine[i] * fontsize);
                if (dropLine[i] * fontsize > height || Math.random() > 0.95){
                    dropLine[i] = 0;
                }
                dropLine[i]++;
            }
        }
    }
    </script>
</head>
<body>
    <canvas id="digitalRain">
    </canvas>
</body>
</html>

2.部分函数和细节讲解

①Math.round(),Math.ceil(),Math.floor()

上面三个函数参数均可以为一个数字,不同之处在于:

Math.round():四舍五入
Math.ceil():向上取整
Math.floor():向下取整

②Math.random()

返回一个在[0,1)范围的随机数

var columns = Math.ceil(width / fontsize); //列数(向上取整)
定义列数时选择使用Math.ceil(),让宽度尽量填充。(右侧空一小部分会很难看...)
var figure = Math.floor(Math.random()*10); //生成0~9的伪随机数
这里使用Math.ceil()向下取整,避免生成10。(一个两位的数字在数字雨里会很突出...)

③绘制数字部分

dropLine这个列表来记录绘制过程,dropLine[i]的意义是表示在第i列,第dropLine[i]行绘制!

ctx.fillText(figure, i * fontsize, dropLine[i] * fontsize);

filltext()是canvas中的方法,这里的三个参数分别对应:内容,横坐标,纵坐标。
坐标是相对于画布的,此处相当于将数字figure绘制到坐标(i * fontsize, dropLine[i] * fontsize)

if (dropLine[i] * fontsize > height || Math.random() > 0.95){
 dropLine[i] = 0;
}
 dropLine[i]++;

当纵坐标超出高度,回至第一行,并设置Math.random()>0.95让其有概率自己回到第一行,这样的数字雨才有感觉~

相关文章

网友评论

      本文标题:canvas+js实现数字雨特效

      本文链接:https://www.haomeiwen.com/subject/rkjgtqtx.html