HTML5 and JS achieve bright moonlight effect

HTML5 and JS achieve bright moonlight effect

First give the renderings:

The source code is as follows:

<!DOCTYPE html>
<html>
<head>
  <title>明媚月光效果</title>
  <style>
    body {
      margin: 0;
      overflow: hidden;
      background-color: #000; /* 添加一个深色背景以便看到月光效果 */
    }
    #moonlightCanvas {
      position: absolute;
      top: 0;
      left: 0;
    }
  </style>
</head>
<body>
  <canvas id="moonlightCanvas"></canvas>

  <script>
    window.addEventListener("load", function() {
      function drawMoonlight() {
        var canvas = document.getElementById("moonlightCanvas");
        var ctx = canvas.getContext("2d");

        canvas.width = window.innerWidth;
        canvas.height = window.innerHeight;

        var centerX = canvas.width / 2;
        var centerY = canvas.height / 2;
        var moonRadius = 50; // 月亮的半径,您可以根据需要调整大小

        // 绘制星星
        function drawStars() {
          var starCount = 50; // 星星的数量
          for (var i = 0; i < starCount; i++) {
            var x = Math.random() * canvas.width;
            var y = Math.random() * canvas.height;
            var starRadius = Math.random() * 2.5; // 星星的大小
            ctx.beginPath();
            ctx.arc(x, y, starRadius, 0, Math.PI * 2, false);
            ctx.fillStyle = "yellow";
            ctx.fill();
          }
	  for (var i = 0; i < starCount; i++) {
            var x = Math.random() * canvas.width;
            var y = Math.random() * canvas.height;
            var starRadius = Math.random() * 2.5; // 星星的大小
            ctx.beginPath();
            ctx.arc(x, y, starRadius, 0, Math.PI * 2, false);
            ctx.fillStyle = "white";
            ctx.fill();
          }
        }

        drawStars(); // 绘制星星

        // 绘制月亮
        ctx.beginPath();
        ctx.arc(centerX, centerY, moonRadius, 0, 2 * Math.PI, false);
        ctx.fillStyle = "rgba(255, 255, 255, 1)"; // 不透明的白色
        ctx.fill();

        // 绘制明媚月光效果
        var gradient = ctx.createRadialGradient(centerX, centerY, moonRadius, centerX, centerY, canvas.width);
        gradient.addColorStop(0, "rgba(173, 216, 230, 0.3)"); // 浅蓝色半透明
        gradient.addColorStop(1, "rgba(255, 255, 255, 0)"); // 完全透明

        ctx.fillStyle = gradient;
        ctx.fillRect(0, 0, canvas.width, canvas.height);
      }

      drawMoonlight();
    });
  </script>
</body>
</html>

Draw a circle representing the moon. The radius of the moon is set to a fixed value (moonRadius = 50;). You can adjust this value according to your needs. Then a larger gradient was added around it to simulate the glowing moonlight effect. You can try changing the gradient's color or transparency. The drawStars function draws stars. This function simulates stars by drawing small dots at random locations on the canvas. The starCount variable controls the number of stars, while the starRadius variable controls the size of each star.

Guess you like

Origin blog.csdn.net/cnds123/article/details/135346575