JSFiddle - React, Tailwind, and code Playground
by Mladen Mihajlovic
HTML
<div id="number-container"></div>
<button id="animate-button">Animate to Random Number</button>
<div>
<div>newFromNumber: <span id="new-from-number"></span></div>
<div>newToNumber: <span id="new-to-number"></span></div>
<div>lastToNumber: <span id="last-to-number"></span></div>
</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 padNumberWithZeros(number, maxDigits) {
const numberString = number.toString();
const integerPart = numberString.split('.')[0];
const fractionPart = numberString.split('.')[1] || '0';
const paddedIntegerPart = integerPart.padStart(maxDigits, '0');
return paddedIntegerPart + '.' + fractionPart;
}
function showDigit(htmlDivElement, spritesheet, numberToShow, percentageFromWhole) {
// 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'));
// Apply the percentageFromWhole to the fraction part
const adjustedFraction = fraction * (1 - percentageFromWhole / 100);
const offsetY = -(wholeNumber * spriteHeight) - (adjustedFraction * spriteHeight);
digit.style.backgroundPositionY = offsetY + 'px';
digitContainer.appendChild(digit);
htmlDivElement.appendChild(digitContainer);
}
function animatePre(htmlDivElement, spritesheet, number, spriteWidth, spriteHeight, durationMilliseconds, maxDigits) {
const startTime = performance.now();
function updateAnimation(currentTime) {
const elapsed = currentTime - startTime;
const progress = elapsed / durationMilliseconds;
if (progress < 1) {
showNumber(htmlDivElement, spritesheet, number, spriteWidth, spriteHeight, -progress * 100, maxDigits);
requestAnimationFrame(updateAnimation);
} else {
showNumber(htmlDivElement, spritesheet, number, spriteWidth, spriteHeight, 0, maxDigits);
}
}
requestAnimationFrame(updateAnimation);
}
function animatePost(htmlDivElement, spritesheet, number,...