skip to Main Content

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.

2

Answers


  1. 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/).

    Login or Signup to reply.
  2. 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', 'black');
        r2.setAttribute('fill', 'white');
        e1.setAttribute('fill', 'black');
        e1.setAttribute('rx', 50 - val * 200);
      } else if (val <= .50) {
        r1.setAttribute('fill', 'black');
        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', 'black');
        e1.setAttribute('fill', 'white');
        e1.setAttribute('rx', 50 - (val-.50) * 200);
      } else if (val <= 1) {
        r1.setAttribute('fill', 'white');
        r2.setAttribute('fill', 'black');
        e1.setAttribute('fill', 'black');
        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="black" />
          <rect id="r2" x="50" y="0" width="50" height="100" fill="black" />
          <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>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search