关闭页面特效

使用canvas实现简易代码雨

分享一个使用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)

代码效果预览


__EOF__

作  者智勇_y
出  处https://www.cnblogs.com/blender-su/p/16707335.html
关于博主:编程路上的小学生,热爱技术,喜欢专研。评论和私信会在第一时间回复。或者直接私信我。
版权声明:署名 - 非商业性使用 - 禁止演绎,协议普通文本 | 协议法律文本
声援博主:如果您觉得文章对您有帮助,可以点击文章右下角推荐一下。您的鼓励是博主的最大动力!

posted @   智勇_y  阅读(67)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
0
0
关注
跳至底部
点击右上角即可分享
微信分享提示