Moon phase graphic in TypeScript incorrectly renders waxing and waning phases

I am working on a React/TypeScript component that renders the phases of the moon based on a value between 0 and 1. The issue is that the moon phases are not rendering correctly between the First Quarter and Last Quarter phases. Specifically, the component shows the moon as waxing when it should be waning, and vice versa.

I tried using a Canvas instead of SVG, but it didn’t resolve the issue. I also tried to change the calculation for the visible portion of the moon to:

const visiblePortion = Math.cos(normalizedPhase * Math.PI * 2);

But the issue didn’t go away. Instead of rendering the moon correctly between 0.25 and 0.75, the light/dark portions of the moon are still reversed for those phases.

Moon Phases on a 0 to 1 Scale

The moon phase is represented as a number between 0 and 1, where:

  • 0: New Moon (0% illumination)
  • 0.125: Waxing Crescent (~25% illumination on the right)
  • 0.25: First Quarter (50% illumination on the right)
  • 0.375: Waxing Gibbous (~75% illumination on the right)
  • 0.5: Full Moon (100% illumination)
  • 0.625: Waning Gibbous (~75% illumination on the left)
  • 0.75: Last Quarter (50% illumination on the left)
  • 0.875: Waning Crescent (~25% illumination on the left)
  • 1: New Moon (0% illumination)

I want the moon to gradually wax between 0 and 0.5 and then wane between 0.5 and 1, but for the phases between 0.25 and 0.75, the light and dark portions are swapped.

Current Code

Here is the code I’m working with:

import React from "react";

interface MoonPhaseProps {
  phase: number;
  moonTexture?: string;
  rotation?: number;
}

const MoonPhase = ({
  phase,
  moonTexture = "/image/moon/moon.svg",
  rotation = 0,
}: MoonPhaseProps) => {
  // Ensure phase is between 0 and 1
  const normalizedPhase = Math.max(0, Math.min(phase, 1));

  console.log(phase, normalizedPhase);

  // Convert phase to radians
  const phaseRadians = normalizedPhase * 2 * Math.PI;

  // Determine if it's a waxing or waning phase
  const isWaxing = normalizedPhase <= 0.5;

  // Calculate the visible portion of the moon
  const visiblePortion = Math.cos(phaseRadians);

  // Adjust the path for waxing and waning phases
  const pathD = isWaxing
    ? `M50,0 A50,50 0 1,1 50,100 A${
        50 * Math.abs(visiblePortion)
      },50 0 1,0 50,0`
    : `M50,0 A50,50 0 1,0 50,100 A${
        50 * Math.abs(visiblePortion)
      },50 0 1,1 50,0`;

  return (
    <svg
      width="100%"
      viewBox="0 0 100 100"
      data-phase={phase}
      style={{
        transform: `rotate(${rotation}deg)`,
        transition: "transform 0.3s ease-in-out",
      }}
    >
      <defs>
        <pattern
          id="moonTexturePattern"
          patternUnits="userSpaceOnUse"
          width="100"
          height="100"
        >
          <image href={moonTexture} x="0" y="0" width="100" height="100" />
        </pattern>

        <mask id="moonMask">
          <rect x="0" y="0" width="100" height="100" fill="white" />
          <path d={pathD} fill="black" />
        </mask>
      </defs>

      {/* Moon texture */}
      <circle cx="50" cy="50" r="49" fill="url(#moonTexturePattern)" />

      {/* Shading for the dark side of the moon */}
      <circle
        cx="50"
        cy="50"
        r="49"
        fill="rgba(0,0,0,0.7)"
        mask="url(#moonMask)"
      />
    </svg>
  );
};

export default React.memo(MoonPhase);

Here’s a sheet (or at least a link to it) showing the moon phases and their values:
moon_phase_explainer

Thanks in advance.

1

I skipped the path and “constructed” the mask from an ellipse. I don’t know if you can use this. In any case, maybe others can.

document.forms.moon.phase.addEventListener('input', e => {
  let e1 = document.getElementById('e1');
  let r1 = document.getElementById('r1');
  let r2 = document.getElementById('r2');
  let val = e.target.value;

  if (val <= .25) {
    r1.setAttribute('fill', '#444');
    r2.setAttribute('fill', 'white');
    e1.setAttribute('fill', '#444');
    e1.setAttribute('rx', 50 - val * 200);
  } else if (val <= .50) {
    r1.setAttribute('fill', '#444');
    r2.setAttribute('fill', 'white');
    e1.setAttribute('fill', 'white');
    e1.setAttribute('rx', (val-.25) * 200);
  } else if (val <= .75) {
    r1.setAttribute('fill', 'white');
    r2.setAttribute('fill', '#444');
    e1.setAttribute('fill', 'white');
    e1.setAttribute('rx', 50 - (val-.50) * 200);
  } else if (val <= 1) {
    r1.setAttribute('fill', 'white');
    r2.setAttribute('fill', '#444');
    e1.setAttribute('fill', '#444');
    e1.setAttribute('rx', (val-.75) * 200);
  }
});
<form name="moon">
  <input name="phase" type="range" min="0" max="1" value="0" step=".01">
</form>
<svg width="200" viewBox="0 0 100 100">
  <defs>
    <pattern id="moonTexturePattern" patternUnits="userSpaceOnUse"
      width="100" height="100">
      <image href="https://upload.wikimedia.org/wikipedia/commons/thumb/e/e1/FullMoon2010.jpg/253px-FullMoon2010.jpg" x="-10" y="-10" width="120" height="120" />
    </pattern>
    <mask id="moonMask">
      <rect id="r1" x="0" y="0" width="50" height="100" fill="#444" />
      <rect id="r2" x="50" y="0" width="50" height="100" fill="#444" />
      <ellipse id="e1" cx="50" cy="50" rx="0" ry="50" fill="black"/>
    </mask>
  </defs>
  <circle cx="50" cy="50" r="49" fill="url(#moonTexturePattern)"
    mask="url(#moonMask)" />
</svg>
<p><a href="https://en.wikipedia.org/wiki/File:FullMoon2010.jpg">Moon image from wikimedia.org</a></p>

5

You want visible portion of the moon to vary from 0 to 100% according to a cos(phase) rule but you have failed to check that your end points in the angle conversion make sense. You seem to want:

cos(0) = 1, cos (pi/2) = 0, cos(pi) = -1

But you have the line setting the phase angle in radians as multiply by 2*pi :

 const visiblePortion = Math.cos(normalizedPhase * Math.PI * 2);

It should read

 const visiblePortion = Math.cos(normalizedPhase * Math.PI);

Where the sign of the visible portion determines which side to hide.

And then it should either be exactly what you want or the opposite (in which case s/cos/sin/).

1

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật