雪花背景

<!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>canvas雪花背景</title>
</head>
<style>
  * {
    padding: 0;
    margin: 0;
  }
  #app {
    width: 100%;
    height: 100vh;
    color: white;
    text-align: center;
  }
</style>
<body>
  <div id="app">
    <h1>标题1</h1>
    <h2>标题2</h2>
    <p>正文...</p>
    <img src="http://zh1q1.net3v.net/wenshuGov/logo.png" alt="">
  </div>

  <script>
    class SnowflakeBground {
      constructor(selector, pixels) {
        this.targetDom = document.querySelector(selector) // 外层盒子选择器
        this.pixels = pixels // 像素点数
        this.renderCanvas()
      }
      renderCanvas() {
        const cvs = document.createElement('canvas')
        const ctx = cvs.getContext('2d')
        const { clientWidth: width, clientHeight: height } = this.targetDom
        cvs.width = width
        cvs.height = height
        ctx.fillStyle = '#fff' // 设置画笔颜色
        // 创建一定长度的空元素数组并赋值,用于创建随机坐标的像素点(范围在外层盒子宽高内)
        const snowPixels = Array.from(new Array(this.pixels)).map(item => {
          return {
            x: Math.random() * width,
            y: Math.random() * height,
            step: Math.random() * 2 + 1 // 步进
          }
        })
        // 渲染函数
        const render = () => {
          ctx.clearRect(0, 0, width, height) // 清空画板
          ctx.beginPath() // 下笔
          snowPixels.forEach(v => {
            v.y = v.y > height ? 0 : (v.y + v.step) // 递进像素点y坐标,让雪花动起来
            ctx.rect(v.x, v.y, 2, 2) // 绘制雪花
          })
          ctx.fill() // 填充
          requestAnimationFrame(render) // 开启动画
        }
        render()
        // 设置背景,不遮盖内层元素
        this.targetDom.style.backgroundColor = 'black';
        this.targetDom.style.position = 'relative';
        cvs.style.position = 'absolute'
        cvs.style.top = 0
        cvs.style.left = 0
        this.targetDom.appendChild(cvs)
      }
    }

    new SnowflakeBground('#app', 400)

  </script>
</body>
</html>

posted on 2022-10-22 00:46  吴知木  阅读(6)  评论(0编辑  收藏  举报

导航