1. 程式人生 > 實用技巧 >canvas滑鼠特效

canvas滑鼠特效

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

<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>
</head>

<body>
  <script>
    let stars = []

    // 配置
    const config = {
      color: false, // 圖案顏色, 如果為false則使用隨機顏色
      size: 0, // 圖案大小, 如果為0則使用隨機大小
      o: 1, // 遞減值,數值越大圖案消失越快
      orange: 30, // 圖案分散程度
      opacity: 0.5, // 圖案透明度,取值 0-1之間,在顏色隨機的情況下有效
    }

    function random(max = 1, min = 0) {
      return parseInt(Math.random() * (max - min)) + min;
    }

    function renderStars(ctx, x, y, size, color) {
      let R = size
      let r = size / 2.5
      //設定是個頂點的座標,根據頂點制定路徑   
      ctx.beginPath()
      for (var i = 0; i < 5; i++) {
        ctx.lineTo(Math.cos((18 + i * 72) / 180 * Math.PI) * R + x,
          -Math.sin((18 + i * 72) / 180 * Math.PI) * R + y);
        ctx.lineTo(Math.cos((54 + i * 72) / 180 * Math.PI) * r + x,
          -Math.sin((54 + i * 72) / 180 * Math.PI) * r + y);
      }
      ctx.closePath()
      ctx.strokeStyle = color
      ctx.stroke()
    }

    window.onmousemove = e => {
      stars.push({
        color: config.color || `rgba(${random(250, 50)}, ${random(240, 0)}, ${random(255, 200)}, ${config.opacity})`,
        x: e.clientX + random(config.orange),
        y: e.clientY + random(config.orange),
        size: config.size || random(20) + 5,
        orange: config.orange,
      })
    }

    function animateTwo(ctx, width, height) {
      ctx.clearRect(0, 0, width, height)
      for (let i = 0; i < stars.length; i++) {
        let item = stars[i]
        item.size -= config.o
        if (item.size <= 0) {
          stars.splice(i, 1)
          i--
        }
        renderStars(ctx, item.x, item.y, item.size, item.color)
      }
      requestAnimationFrame(animateTwo.bind(this, ctx, width, height))
    }

    window.onload = function () {
      const width = document.documentElement.clientWidth
      const height = document.documentElement.clientHeight
      const cvs2 = document.createElement('canvas')
      document.body.appendChild(cvs2)
      const ctx2 = cvs2.getContext('2d')
      cvs2.style.zIndex = 200;
      cvs2.style.position = 'fixed'
      cvs2.style.top = 0;
      cvs2.style.left = 0
      cvs2.style.right = 0
      cvs2.style.bottom = 0
      cvs2.style.pointerEvents = 'none'
      cvs2.width = width;
      cvs2.height = height;
      animateTwo(ctx2, width, height)
    }
  </script>
</body>

</html>