使用TS实现代码雨

103 阅读1分钟

ok这期我们直接话不多说上代码,效果图我放在封面了。没错,封面就是。

大家感兴趣的可以直接复制使用。想要什么文字直接修改str变量

const canvas: HTMLCanvasElement | null = document.querySelector('#canvas')

const str = 'china'.split('')
const arr = Array( Math.floor(screen.availWidth / 10) ).fill(0)

const rain = (ctx: CanvasRenderingContext2D) => {
    ctx.fillStyle = 'rgba(0, 0, 0, 0.15)'
    ctx.fillRect(0, 0, screen.availWidth, screen.availHeight)
    ctx.fillStyle = '#0f0'
    arr.forEach((item, index) => {
        ctx.fillText(str[Math.floor( Math.random() * str.length )], index * 10, item + 10)
        arr[index] = item > canvas!.width || item > 10000 * Math.random() ? 0 : item + 10
    })
}

if (canvas) {
    // 将canvas的宽高设置为屏幕宽高
    canvas!.width = screen.availWidth
    canvas!.height = screen.availHeight
    const ctx = canvas.getContext('2d') as CanvasRenderingContext2D
    setInterval(rain, 50, ctx)
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <canvas id="canvas"></canvas>
    <script src="./code-rain.js"></script>
</body>
</html>