JSFiddle - React, Tailwind, and code Playground

by Mladen Mihajlovic

HTML

<div id="number-container"></div>

CSS

.digit-container {
  width: var(--sprite-width);
  height: var(--sprite-height);
  overflow: hidden;
  position: relative;
  display: inline-block;
}

.digit {
  position: absolute;
  width: var(--sprite-width);
  height: calc(20 * var(--sprite-height));
  background-repeat: repeat-y;
}

.number-wrapper {
  display: flex;
}

JavaScript

function showDigit(htmlDivElement, spritesheet, numberToShow) {
   // Create the digit container
   const digitContainer = document.createElement('div');
   digitContainer.classList.add('digit-container');

   const digit = document.createElement('div');
   digit.classList.add('digit');
   digit.style.backgroundImage = `url(${spritesheet})`;

   const wholeNumber = Math.floor(numberToShow) % 10;
   const fraction = numberToShow - wholeNumber;

   const spriteHeight = parseFloat(getComputedStyle(document.documentElement).getPropertyValue('--sprite-height'));
   const offsetY = -(wholeNumber * spriteHeight) - (fraction * spriteHeight);
   digit.style.backgroundPositionY = offsetY + 'px';

   digitContainer.appendChild(digit);
   htmlDivElement.appendChild(digitContainer);
 }

 function showNumber(htmlDivElement, spritesheet, numberToShow, spriteWidth, spriteHeight) {
   htmlDivElement.innerHTML = ''; // Clear the container before displaying a new number

   const rootStyle = document.documentElement.style;
   rootStyle.setProperty('--sprite-width', spriteWidth + 'px');
   rootStyle.setProperty('--sprite-height', spriteHeight + 'px');

   const numberString = numberToShow.toString();
   const integerPart = numberString.split('.')[0];
   const fractionPart = numberString.split('.')[1] || '0';

   const numberWrapper = document.createElement('div');
   numberWrapper.classList.add('number-wrapper');
   htmlDivElement.appendChild(numberWrapper);

   for (let i = 0; i < integerPart.length; i++) {
     const currentDigit = parseInt(integerPart.charAt(i), 10);
     const nextDigit = i < integerPart.length - 1 ? parseInt(integerPart.charAt(i + 1), 10) : parseInt(fractionPart.charAt(0), 10);
     const container = document.createElement('div');
     container.id = `digit_${i + 1}`;
     numberWrapper.appendChild(container);
     showDigit(container, spritesheet, currentDigit + nextDigit / 10);
   }
 }

 function animateNumber(htmlDivElement, spritesheet, fromNumber,...