Canvas 实现背景星星闪烁 Stars twinkle

Stars twinkle canvas

可以精确控制星星数量,闪烁频率,透明度,尺寸等。

<style>
  #starCanvas{
    position: fixed;
    width: 100vw;
    height: 100vh;
    z-index: 0;
    top:0;
    left:0;
    right:0;
    opacity: 0.8;
  }
</style>

<canvas id="starCanvas"></canvas>
<script>
  // Get the canvas element and set its size
  const canvas = document.getElementById('starCanvas');
  const ctx = canvas.getContext('2d');
  canvas.width = window.innerWidth;
  canvas.height = window.innerHeight;
   
  // Star properties
  const numStars = 120;
  const starRadius = 0.7; // Fixed radius for all stars
  const stars = [];
  for (let i = 0; i < numStars; i++) {
    stars.push({
      x: Math.random() * canvas.width,
      y: Math.random() * canvas.height,
      radius: starRadius,
      opacity: Math.random(), // Random opacity between 0 and 1
      twinkleSpeed: Math.random() * 2 + 0.5, // Random twinkle speed between 0.5 and 2.5 seconds
      lastTwinkleTime: Math.random() * 1000 // Random start time for twinkling
    });
  }
   
  // Function to draw stars
  function drawStars() {
    ctx.clearRect(0, 0, canvas.width, canvas.height); // Clear the canvas
    stars.forEach(star => {
      ctx.save();
      ctx.globalAlpha = star.opacity; // Set opacity
      ctx.beginPath();
      ctx.arc(star.x, star.y, star.radius, 0, Math.PI * 2); // Draw circle with the star's radius
      ctx.fillStyle = 'white';
      ctx.fill();
      ctx.restore();
    });
  }
   
  // Function to twinkle stars
  function twinkleStars() {
    const now = Date.now();
    stars.forEach(star => {
      const deltaTime = now - star.lastTwinkleTime;
      if (deltaTime > star.twinkleSpeed * 1000) {
        star.opacity = Math.random(); // Randomly change opacity
        star.lastTwinkleTime = now; // Reset the twinkle time
      }
    });
  }
   
  // Animation loop
  function animate() {
    drawStars();
    twinkleStars();
    requestAnimationFrame(animate);
  }
   
  // Start the animation
  animate();
   
  // Resize canvas when the window is resized
  window.addEventListener('resize', () => {
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;
  });
  </script>

原文链接:https://store.606design.art/archives/268.html,转载请注明出处。
0

评论0

显示验证码
没有账号?注册  忘记密码?