美文网首页
画布实现代码雨效果

画布实现代码雨效果

作者: 修修修xiao | 来源:发表于2017-12-27 11:38 被阅读0次
    捕获.PNG

    代码如下:

    <!DOCTYPE html>
    <html>
        <head>
            <meta charset="utf-8">
            <title></title>
            <style>
                *{
                    padding:0;
                    margin:0;
                }
                html{
                    overflow:hidden;
                    /*溢出隐藏*/
                }
          </style>
        </head>
        <body>
            <canvas id="canvas" style="background-color:#111"></canvas>
        </body>
        <script type="text/javascript">
            // 获取到画布对象
            var canvas = document.querySelector('canvas');
            // 获取到画布上下文(画笔)
            var cxt = canvas.getContext('2d');
            //获取浏览器窗口的宽度和高度
            var W = window.innerWidth;
            var H = window.innerHeight;
            //设置canvas的宽度和高度
            canvas.width = W;
            canvas.height = H;
            // 设置每个字体的大小
            var fontSize = 16;
            // 计算窗口可以排放多少列
            var colunms = Math.floor(W /fontSize);
            //记录每列文字的y轴坐标
            var drops = [];
            //给每一个文字初始化一个起始点的位置
            for(var i = 0;i < colunms; i++){
                drops.push(0);
    
            }
            console.log(drops);
            // 设置代码雨的运动文字
            var str = 'dfsgwehfhjfwtwwtwgfgwtwr2rwfefswgwtwt ';
    
            // 绘画的函数
            function draw() {
                cxt.beginPath();//起始一条路径,或重置当前路径。
                cxt.fillStyle = "rgba(0,0,0,0.05)";//将其染色
                cxt.fillRect(0,0,W,H);// 规定了形状位置和尺寸
                cxt.beginPath();//起始一条路径,或重置当前路径。
                // 给字体设置样式
                cxt.font = fontSize + 'px 微软雅黑';
                // 给字体添加颜色
                cxt.fillStyle = '#22ff22';
                // 写入画布中
                for(var i=0;i<colunms;i++){
                    // 设置随机字母
                    var index = Math.floor(Math.random() * str.length);
                    var x = i*fontSize;
                    var y = drops[i] *fontSize;
                    // console.log(fontSize);
                    console.log('x:'+ x + '----'+ 'y:' + y)
                    cxt.fillText(str[index],x,y);//在画布上绘制填色的文本
                    //如果要改变时间,肯定就是改变每次他的起点
                    if(y >= canvas.height && Math.random() > 0.99){
                        drops[i] = 0;
                    }
                    drops[i]++;
                }
            };
    
            draw();
            setInterval(draw,30);
    
    
        </script>
    </html>
    
    

    相关文章

      网友评论

          本文标题:画布实现代码雨效果

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