首页 > 其他分享 >使用canvas实现简易代码雨

使用canvas实现简易代码雨

时间:2022-09-19 12:33:39浏览次数:64  
标签:canvas const width 代码 ctx height 简易 columnNextIndexes Math

分享一个使用canvas生成的一个简易代码雨特效

首先HTML文件如下

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

Javascript 代码如下

const cvs = document.getElementById('bg')
const width = window.innerWidth,
    height = window.innerHeight

//设置canvas窗口尺寸
cvs.width = width
cvs.height = height

// 获取绘制上下文
const ctx = cvs.getContext('2d')

// 列宽
const columnWidth = 20

//列数
const columnCount = Math.floor(width / columnWidth)

// 记录每列写到了第几个文字
const columnNextIndexes = new Array(columnCount)
columnNextIndexes.fill(1)


function getRandomColor() {
    const fontColors = [
        '#33b5e5',
        '#0099cc',
        '#aa66cc',
        '#9933cc',
        '#99cc00',
        '#669900',
        '#ffbb33',
        '#ff8800',
        '#ff4444',
        '#cc0000',

    ]
    return fontColors[Math.floor(Math.random() * 10)]
}
function getRandomChar() {
    const str = 'console.log("Hello World")'
    return str[Math.floor(Math.random() * str.length)]
}
function draw() {
    ctx.fillStyle = 'rgba(255,255,255,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 * columnNextIndexes[i]
        ctx.fillText(getRandomChar(),x,y)
        if (y > height && Math.random() > 0.99){
            columnNextIndexes[i] = 0
        }else {
            columnNextIndexes[i]++
        }

    }
}

// 定时渲染
setInterval(draw,40)

代码效果预览

标签:canvas,const,width,代码,ctx,height,简易,columnNextIndexes,Math
From: https://www.cnblogs.com/blender-su/p/16707335.html

相关文章