代码雨(前端实现)

代码雨(前端实现)_第1张图片

HTML

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    * {
      padding: 0;
      margin: 0;
      overflow: hidden;
    }
  </style>
</head>

<body>
  <canvas id="canvas"></canvas>
  <script src="./index.js"></script>
</body>

</html>

JS版

var canvas = document.querySelector('canvas');
var ctx = canvas === null || canvas === void 0 ? void 0 : canvas.getContext('2d');
canvas.width = screen.availWidth;
canvas.height = screen.availHeight;
var strArr = 'dsfhbskcvhiowenfbsdhnvwoierfqffa0131234678312'.split('');
var arr = new Array(Math.ceil(canvas.width / 10)).fill(0);
var rain = function () {
    ctx.fillStyle = 'rgba(0,0,0,0.1)';
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    ctx.fillStyle = '#0f0';
    arr.forEach(function (item, index) {
        ctx === null || ctx === void 0 ? void 0 : ctx.fillText(strArr[Math.floor(Math.random() * strArr.length)], index * 10, item + 10);
        arr[index] =
            item > screen.availHeight || item > 10000 * Math.random() ? 0 : item + 10;
    });
};
setInterval(rain, 40);

TS版

let canvas: HTMLCanvasElement | null = document.querySelector('canvas')
let ctx = canvas?.getContext('2d')
canvas!.width = screen.availWidth
canvas!.height = screen.availHeight

let strArr: string[] = 'dsfhbskcvhiowenfbsdhnvwoierfqffa0131234678312'.split('')
let arr = new Array(Math.ceil(canvas!.width / 10)).fill(0)

let rain = () => {
  ctx!.fillStyle = 'rgba(0,0,0,0.1)'
  ctx!.fillRect(0, 0, canvas!.width, canvas!.height)
  ctx!.fillStyle = '#0f0'
  arr.forEach((item, index) => {
    ctx?.fillText(
      strArr[Math.floor(Math.random() * strArr.length)],
      index * 10,
      item + 10
    )
    arr[index] =
      item > screen.availHeight || item > 10000 * Math.random() ? 0 : item + 10
  })
}

setInterval(rain, 40)

你可能感兴趣的:(typescript,js,前端)