Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Auto Save

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <figure></figure>

<button>Refresh</button>
              
            
!

CSS

              
                * {
  font-family: sans-serif;
}

html, body {
  display: grid;
  height: 100%;
  place-items: center;
  gap: 1em;
}

button {
  padding: 1em 2em;
}

.u-visually-hidden {
  border: 0;
  clip: rect(0 0 0 0);
  clip-path: polygon(0 0, 0 0, 0 0);
  height: 1px;
  margin: -1px;
  overflow: hidden;
  padding: 0;
  position: absolute;
  white-space: nowrap;
  width: 1px;
}

///
/// Our component container
///
/// 1. Position our children in a single area
///
.circle-meter {
  --meter-stroke-width: 3px;
  color: #f2f5f7;
  display: inline-grid;
  grid-template-areas: 'content'; // 1
  place-items: center; // 1
  padding: var(--meter-stroke-width);
  background-color: #0e1c43;
  border-radius: 50%;
  aspect-ratio: 1;
  // This is a magic number, but ensures the meter is large enough to display
  // a percentage with a single decimal point.
  width: 11rem;
}

.circle-meter > * {
  grid-area: content; // 1
}

///
/// Our actual percent is big and bold.
///
/// 1. We undo the tracking change. Since we're just showing a number, the
///    uppercase styling doesn't have any effect.
///
.circle-meter__percent {
  font-weight: bold;
  font-size: 2rem;
  letter-spacing: initial; // 1
  line-height: 1.1;
}

// Make sure our "gauge" graphic fills the container
.circle-meter__gauge {
  width: 100%;
  height: 100%;
}

///
/// The animated circle stroke
///
/// 1. We do some math to determine our circle's circumference. This gives us
///    the length of the stroke on our circle
/// 2. With more math we can determine how much of our circle's stroke should
///    be left undrawn (e.g. if our value is 75%, 25% of the stroke should be
///    undrawn. We need this in pixels.)
/// 3. Use SVG stroke drawing to only draw the relevant part of our stroke
///    @see https://css-tricks.com/svg-line-animation-works/
/// 4. By default, a circle's stroke starts on its right edge. We want it to
///    start from the top. We rotate the circle to achieve this
/// 5. Animate the stroke animation
///
.circle-meter__circle {
  --radius: 47px; // 1
  --pi: 3.14; // 1 - Close enough for our use case!
  --circumference: calc(var(--radius) * 2 * var(--pi)); // 1
  --stroke-length: var(--circumference); // 1
  --stroke-offset: calc(
    var(--circumference) - (var(--circumference) * var(--percent) / 100)
  ); // 2

  fill: none;
  r: var(--radius); // 1
  rotate: -90deg; // 4
  stroke: #3d84f5;
  stroke-dasharray: var(--stroke-length); // 3
  stroke-dashoffset: var(--stroke-offset); // 3
  stroke-width: var(--meter-stroke-width);
  transform-origin: center; // 4

  @media (prefers-reduced-motion: no-preference) {
    animation: stroke 750ms both; // 5
  }
}

@keyframes stroke {
  from {
    stroke-dashoffset: var(--stroke-length);
  }
  to {
    stroke-dashoffset: var(--stroke-offset);
  }
}
              
            
!

JS

              
                const duration = 750;

let animationFrameId = 0;

function draw() {
  cancelAnimationFrame(animationFrameId);
  
  const endValue = (15 + Math.random() * 75).toFixed(1);
  document.querySelector('figure').innerHTML = `
    <div class="circle-meter">
      <p class="circle-meter__text">
        <span class="circle-meter__percent" id="meter-label">
          <!--
            For screen reader users we hide the animated value,
            because it could be noisy and overwhelming.
            We expose the end value
          -->
          <span class="u-visually-hidden">${endValue}%</span>
          <span aria-hidden="true"><span class="animated-count">0</span>%</span>
        </span>
      </p>
      <!-- I'm exposing this as a meter element, but I'm not sure if that's the best experience or not.  -->
      <svg
           width="100"
           height="100"
           viewBox="0 0 100 100"
           class="circle-meter__gauge"
           role="meter"
           aria-labelledby="meter-label"
           aria-valuemin="0"
           aria-valuemax="100"
           aria-valuenow="${endValue}"
      >
        <circle
                cx="50"
                cy="50"
                class="circle-meter__circle"
                style="--percent: ${endValue}"
        />
      </svg>
    </div>
  `;
  
  if(window.matchMedia('(prefers-reduced-motion: reduce)').matches) {
    document.querySelector('.animated-count').textContent = endValue;
    return;
  }
  
  // Our start time (to determine where we are in the animation)
  const startTime = performance.now();
  // An array of the values that we'll be iterating through and displaying
  // e.g. [1, 2, 3, ... 73, 74, 74.1, 74.2, 74.3]
  const animationStates = determineAnimationStates(endValue);
  
  function animate() {
    // Compare our current time with our start time
    let elapsedTime = performance.now() - startTime;

    // If we've exceeded our duration, pretend we're right at the end of the
    // animation.
    if (elapsedTime > duration) {
      elapsedTime = duration;
    }

    // See how far we are compared to the total duration
    const percentComplete = elapsedTime / duration;
    // Use that value to select a frame to display
   
    document.querySelector('.animated-count').textContent = animationStates[
        Math.round(percentComplete * (animationStates.length - 1))
      ]

    // If we haven't hit the end of our animation, queue up another frame
    if (elapsedTime < duration) {
      animationFrameId = requestAnimationFrame(animate);
    }
  }
  
  animationFrameId = requestAnimationFrame(animate);
}

draw();

document.querySelector('button').addEventListener('click', draw)


/**
 * Determines all of the animation frames necessary to animate from 0 to another
 * number.
 *
 * This function allows for up to one level of decimal point precision.
 * However, decimals are only displayed for the final integer in the animation.
 *
 * For example, if we're animating to 74.3, our returned array would look like this:
 * [1, 2, 3, ... 73, 74, 74.1, 74.2, 74.3]
 *
 * This is because if we displayed every decimal along the way we'd end up with
 * an order of magnitude more animation states. If we tried to animate that in
 * a short time frame it would be more animation frames than a human could observe.
 * (e.g. trying to display 743 frames in 750 milliseconds)
 */
export function determineAnimationStates(endValue) {
  const animationStates = [];

  // Get our number rounded down
  const roundedValue = Math.floor(endValue);
  // Get every integer between 1 and our rounded down number
  // [1, 2, 3, ... 73, 74]
  for (let i = 1; i <= roundedValue; i++) {
    animationStates.push(i);
  }

  // Determine whether there's anything in the first decimal place for us to
  // worry about
  const remainder = parseFloat((endValue - roundedValue).toFixed(2));

  // Iterate over our first decimal place, adding the final decimal states
  // [..., 74.1, 74.2, 74.3]]
  if (remainder) {
    // Originally my loop looked like this:
    // `for (let i = 0.1; i <= 0.3; i += 0.1) {}`
    // This was buggy due to floating point precision in JS (0.2 + 0.1 = 0.30000000000000004)
    // Using integers instead of decimals makes the code a bit more complex
    // but fixes this.
    for (let i = 1; i <= remainder * 10; i += 1) {
      animationStates.push(roundedValue + i / 10);
    }
  }

  return animationStates;
}
              
            
!
999px

Console