js实现代码雨效果

242 阅读1分钟

读前说明

本篇文章记录了如何在html使用js在canvas上绘制代码雨的效果,主要是进行canvas绘制的一次简单尝试

js实现代码雨效果

前期准备

在页面中插入canvas画布

<canvas id="bg"></canvas>

利用js脚本

        const cvs=document.getElementById('bg')
        const width=window.innerWidth
        const height=window.innerHeight
        
        cvs.width=width
        cvs.height=height
​
        const ctx=cvs.getContext('2d')
​
        // 列宽
        const columnWidth=20
       
        //列数
        const columnCount=Math.floor(window.innerWidth/columnWidth)
        //记录每列写到了第几个文字
        const columnNestIndexes=new Array(columnCount);
        columnNestIndexes.fill(1)
​
        //绘画的函数
        function draw(){
          ctx.fillStyle='rgba(240,240,240,0.1)'
          ctx.fillRect(0,0,width,height)
          const fz=20
          ctx.fillStyle=getRandomColor()
          ctx.font=`${fz}px "Roboto Mono"`
          for(let i=0;i<columnCount;i++){
           const x=i*columnWidth
           const y=fz*columnNestIndexes[i]
           ctx.fillText(getRandomChar(),x,y)
           if(y>height&&Math.random()>0.99){
            columnNestIndexes[i]=0
           }
           else{
            columnNestIndexes[i]++
           }
          }
         
        }
        //随机颜色 
        function getRandomColor(){
            const fontColors=[
                '#33B5E5',
                '#0099cc',
                '#AA6655',
                '#9933cc',
                '#99cc00',
                '#669900',
                '#ffbb33',
                '#ff8800',
                '#ff8844',
                '#cc0000',
            ]
            return  fontColors[Math.floor(Math.random()* fontColors.length)]
        }
         
        //随机文字
        function getRandomChar(){
            const str='console.log("hello word")'
            return str[Math.floor(Math.random()*str.length)]
        }
        setInterval(draw, 40);

成品展示

uTools_1680516915197.png

总结

整体思路就是在canvas基础上,生成随机颜色的随机字符串,计算出屏幕的列数,在进行绘制