直接上源碼吧玷氏,作為一個(gè)新手罩抗,玩一玩開心就好
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>rain</title>
<style type="text/css">
* {
margin: 0;
padding: 0;
}
body {
overflow: hidden;
}
#canvas {
margin:0 auto;
}
</style>
</head>
<body>
<canvas id="canvas" width='300px' height="200px">
Your browser doesn't support the canvas'.
</canvas>
<script type="text/javascript">
// 可設(shè)置 density = 1, 幫助理解代碼原理
const config = {
// 背景初始值
background: 'rgba(0,0,0,0.1)',
// 字體
font_size: 16,
// 字體 css 屬性
font: '16px arial',
// 字體色
color: '#0F0',
// 展示的字體數(shù)組
charsArr: '0123456789qwertyuiopasdfghjklzxcvbnm'.split(''),
// 消失率閾值, 可以調(diào)整 density 來(lái)調(diào)整密度
density: 0.95,
// 獲取隨機(jī)字符
randomChar: (chars) => {
return chars[Math.floor(Math.random() * chars.length)]
},
}
// 初始化 dom, 繪圖上下文 context, 存儲(chǔ)數(shù)據(jù)的'篩子' boult
const init = () => {
const canvas = document.querySelector('canvas')
canvas.width = screen.width
canvas.height = screen.height
let columns = Math.floor(canvas.width / config.font_size)
let boult = new Array(columns).fill(1)
// 全屏事件綁定
canvas.addEventListener('click', () => {
if(canvas.webkitRequestFullScreen){
canvas.webkitRequestFullScreen()
}else if(canvas.mozRequestFullScreen){
canvas.mozRequestFullScreen()
}else if(canvas.requestFullScreen){
canvas.requestFullscreen()
}else{
console.log("your bowser doesn't support fullscr.")
}
})
const context = canvas.getContext('2d')
return {
canvas, context, boult
}
}
const draw = (canvas, context, boult) => {
const { background, color, font_size, font, charsArr, density } = config
// 函數(shù)分開取, 不然代碼多了分不清
const { randomChar } = config
// 不斷繪制透明度為0.1的長(zhǎng)方形實(shí)現(xiàn)由灰變黑的過(guò)程,同時(shí)之前的字也會(huì)逐漸被覆蓋,然后消失
context.fillStyle = background
context.fillRect(0, 0, canvas.width, canvas.height)
context.fillStyle = color
context.font = font
for(let i = 0; i < boult.length; i++) {
let text = randomChar(charsArr)
let posX = i*font_size
let posY = boult[i]*font_size
context.fillText(text, posX, posY)
if(posY > canvas.height || Math.random() > density) {
//超出屏幕或者產(chǎn)生隨機(jī)數(shù)超過(guò)density即重置這一個(gè)字符到初始位置
boult[i] = 0
}
// 實(shí)現(xiàn)下滑
boult[i]++
}
}
const __main = () => {
const { canvas, context, boult } = init()
setInterval(()=>{
draw(canvas, context, boult)
}, 1000/40)
}
__main()
</script>
</body>
</html>
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者