利用Canvas的fillText(),隔一定时间在画布上作画
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<style>
* {
margin: 0;
padding: 0;
}
body {
overflow: hidden
}
</style>
</head>
<body>
<canvas id='canvas' style='background:#111'></canvas>
<script>
canvas = document.getElementById('canvas')
context = canvas.getContext('2d')
//定义画布大小,字体,颜色
var W = window.innerWidth
var H = window.innerHeight
canvas.height = H
canvas.width = W
var fontSize = 16
var colunms = Math.floor(W / fontSize)
var drops = [] //drops中是每列字母y坐标的倍数
for (let i = 0; i < colunms; i++) {
drops.push(1000)
}
var str = 'qwertyuiopasdfghjklmnbvcxzQWERTYUIOPLKJHGFDSAZXCVBNM0123456789'
function draw() {
//每次draw(),设置透明度可以显示上一次draw()的图像,形成残影
context.fillStyle = 'rgba(0, 0, 0, 0.05)'
context.fillRect(0, 0, W, H)
context.font = '1000 ' + fontSize + 'px Consolas'
context.fillStyle = '#00cc33'
context.textAlign = 'center'
for (let i = 0; i < colunms; i++) {
let index = Math.floor(Math.random() * str.length)
let x = i * fontSize
let y = drops[i] * fontSize
//在x,y坐标中随机画str中的一个字符
context.fillText(str[index], x, y)
//y大于画布高度后,设置随机数,规定是否从顶点重新开始画
if (y >= H && Math.random() > 0.99) {
drops[i] = 0
}
//每次draw()后,倍数加一,下一个字符画在它的下方
drops[i]++
}
}
window.onload = function () {
setInterval(draw, 50)
}
</script>
</body>
还可以设置字体的随机颜色,使动画更绚丽
添加randColor函数,并更改draw
function draw() {
context.fillStyle = 'rgba(0, 0, 0, 0.05)'
context.fillRect(0, 0, W, H)
context.font = '1000 ' + fontSize + 'px Consolas'
context.textAlign = 'center'
for (let i = 0; i < colunms; i++) {
context.fillStyle = randColor()
let index = Math.floor(Math.random() * str.length)
let x = i * fontSize
let y = drops[i] * fontSize
context.fillText(str[index], x, y)
if (y >= H && Math.random() > 0.99) {
drops[i] = 0
}
drops[i]++
}
}
function randColor() {
let r = Math.floor(Math.random() * 256)
let g = Math.floor(Math.random() * 256)
let b = Math.floor(Math.random() * 256)
return `rgb(${r},${g},${b})`
}