赞
踩
上代码
- <!DOCTYPE html>
- <html lang="en">
-
- <head>
- <meta charset="UTF-8" />
- <meta name="viewport" content="width=device-width, initial-scale=1.0" />
- <meta http-equiv="X-UA-Compatible" content="ie=edge" />
- <title>代码雨</title>
- <style>
- * {
- padding: 0;
- margin: 0;
- }
-
- body {
- overflow: hidden;
- }
- </style>
- </head>
-
- <body>
- <canvas id="rain" style="background-image: linear-gradient(blue,red,yellow)"></canvas>
- <script>
- <!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>代码雨</title>
- </head>
-
- <body>
- <canvas id="rain" style="background-image: linear-gradient(blue, black, red);"></canvas>
- </body>
- <script>
- class CodeRain {
- constructor(canvas, width, height, fontSize) {
- this.fontSize = fontSize
- // 保存画布为类变量,方便使用
- this.canvas = canvas
- this.canvas.width = width
- this.canvas.height = height
- // 拿到画笔
- this.pencel = canvas.getContext("2d")
- // 画布的宽
- this.width = width
- // 画布的高
- this.height = height
- // 计算列数
- const columnsNum = Math.floor(width / fontSize)
- // 初始化数组长度
- this.drops = new Array(columnsNum)
- // 设置数组的初始值
- this.drops.fill(1)
- }
- // 获取随机字符
- getRandomStr() {
- return Math.random().toString(36).slice(12).substr(0, 1)
- }
-
- // 获取随机颜色
- getRandomColor() {
- const r = Math.floor(Math.random() * 256)
- const g = Math.floor(Math.random() * 256)
- const b = Math.floor(Math.random() * 256)
- return `rgb(${r},${g},${b})`
- }
-
- // 鬼画符
- draw() {
- // 设置覆盖色
- this.pencel.fillStyle = "rgba(0,0,0,0.1)"
- this.pencel.fillRect(0, 0, this.width, this.height)
- // 设置字体样式
- this.pencel.font = `600 ${this.fontSize}px 微软雅黑`
- // 设置字体的填充颜色
- this.pencel.fillStyle = this.getRandomColor()
- // 有多少列就画多少个字符
- this.drops.forEach((item, index) => {
- // 设置x方向的坐标
- const x = index * this.fontSize
- // // 设置Y方向坐标
- const y = this.drops[index] * this.fontSize
- // // 设置需要填充的字体
- this.pencel.fillText(this.getRandomStr(), x, y)
- if (y > this.height && Math.random() > 0.99) {
- this.drops[index] = 0
- }
- this.drops[index]++
- })
- }
- }
- // 获取画布节点
- let el = document.getElementById("rain")
- const _w = window.innerWidth
- const _h = window.innerHeight
- // 创建画布实例,传入必要参数
- let codeRain = new CodeRain(el, _w, _h, 16)
- setInterval(() => {
- codeRain.draw()
- }, 30);
-
- </script>
-
- </html>
- </script>
- </body>
-
- </html>
写这篇文章的目的呢仅仅是为了练习以下js。离职状态长时间不写代码容易手生
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。