一、功能描述
使用canvas实现一个代码雨的功能,炫一个~~~
二、上码
html
html
<canvas id="canvas"></canvas>
js
javascript
let canvas = document.querySelector('canvas');
let ctx = canvas.getContext('2d');
// screen.availWidth:可视区域的宽度
canvas.width = screen.availWidth;
canvas.height = screen.availHeight;
let str = 'zyk01010168'.split('');
const px = 10;
let arr = Array(Math.ceil(canvas.width / px )).fill(0)
const rain = () => {
//使用,0.05模糊,每次都重叠绘制。看出虚幻的效果
ctx.fillStyle = 'rgba(0,0,0,0.05)';
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = '#00FF00';
arr = arr.map((ele,index) => {
//横向间隔px的距离显示字母
ctx.fillText(str[Math.floor(Math.random() * str.length)], index * px, ele + px);
//修改纵向坐标
return (ele > canvas.height || ele > 5000 * Math.random()) ? 0 : ele+ 10
});
}
setInterval(rain, 40)