Code rain effect:
Implementation method:
①Create a folder to store the project, eg: "rainTS", and create "tsconfig.json", "index.ts", and "index.html" in sequence
"tsconfig.json" creation method: "tsc --init"
After creating the "index.ts" file, you can use the "tsc -w" command to enable ts file monitoring, and generate the corresponding js file from the ts file: "index.ts "–""index.js", do not close the command window after opening the monitor, and after changing the ts file later, the corresponding latest js file will be generated in time
The project structure is as follows:
②Modify the "tsconfig.json" file configuration
Modify the "target" and "lib" configurations as needed
③ Edit the "index.html" file
, add the canvas tag, and add the id attribute to it, so that it is convenient to obtain element nodes for drawing operations
Code example:
<!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="canvas"></canvas>
<script src="./index.js"></script>
</body>
</html>
④ Edit the "index.ts" file
a. Obtain the canvas element, create a 2d drawing rendering object, and use the width and height of the browser window as the width and height of the drawing
b. Create a string array to store the code rain content to be displayed , and other data can also be stored
c. Create a digital array to store the initial position of the code rain data, here I am from top to bottom, the initial position is "0", leaving 10 pixel positions for each element
d .Create a function to control the position movement of the element
e. Create a cycle timer, and execute the movement function repeatedly regularly, so that the element moves to form a rain effect
Code example:
let canvas:HTMLCanvasElement = document.querySelector('canvas') as HTMLCanvasElement
let ctx = canvas.getContext('2d')
canvas.width = screen.availWidth
canvas.height = screen.availHeight
let str:string[] = 'todayisagoodday!'.split('')
let Arr:number[] = Array(Math.ceil(canvas.width / 10)).fill(0)
console.log(Arr);
const rain = () => {
ctx!.fillStyle = 'rgba(0,0,0,.05)'
ctx?.fillRect(0, 0, canvas.width, canvas.height)
ctx!.fillStyle = 'gold'
Arr.forEach((item, index) => {
ctx?.fillText(str[Math.floor(Math.random() * str.length)], index * 10, item + 10)
Arr[index] = item > canvas.height || item > 10000 * Math.random() ? 0 : item + 10
})
}
setInterval(rain, 40)