如何用貝塞爾曲線實現數字動態增長的分段展示效果?

如何用貝塞爾曲線實現數字動態增長的分段展示效果?

使用JavaScript和貝塞爾曲線實現數字動態增長的分段展示效果

本文演示如何利用JavaScript中的貝塞爾曲線函數,精確控制數字的動態增長速度,并實現數字分段顯示的效果。目標是將數字從0增長到1000,增長速度由貝塞爾曲線控制,并分段顯示數字。

核心思路是:利用貝塞爾曲線計算不同時間點的增長比例,并將此比例應用于目標數字的增長。通過調整貝塞爾曲線的控制點,可以改變增長速度的曲線形狀。

以下代碼片段展示了實現方法:

// 貝塞爾曲線控制點 const startX = 0; const startY = 0; const cp1X = 0.1; const cp1Y = 0.4; const cp2X = 0.1; const cp2Y = 1; const endX = 1; const endY = 1;  // 貝塞爾曲線函數 function bezier(t) {   const cx = 3 * (cp1X - startX);   const cy = 3 * (cp1Y - startY);   const bx = 3 * (cp2X - cp1X) - cx;   const by = 3 * (cp2Y - cp1Y) - cy;   const ax = endX - startX - cx - bx;   const ay = endY - startY - cy - by;   const x = ax * t * t * t + bx * t * t + cx * t + startX;   const y = ay * t * t * t + by * t * t + cy * t + startY;   return y; }  // 數字增長動畫 let count = 0; const target = 1000; const duration = 3000; // 動畫持續時間 (毫秒) const startTime = Date.now();  function update() {   const elapsed = Date.now() - startTime;   const t = Math.min(1, elapsed / duration);   count = Math.round(bezier(t) * target);    // 分段顯示數字 (示例:每100遞增顯示一次)   const displayCount = Math.floor(count / 100) * 100;   document.getElementById('count').textContent = displayCount;    if (elapsed < duration) {     requestAnimationFrame(update);   } }  update();

這段代碼定義了貝塞爾曲線的控制點,bezier 函數計算給定時間 t 對應的 y 坐標(即增長比例)。update 函數根據時間推移計算當前增長比例,并更新 count 值。 為了實現分段顯示,代碼中增加了 displayCount 變量,只顯示100的倍數。 最后,requestAnimationFrame 保證動畫流暢。 需要在html中添加一個 id=”count” 的元素來顯示數字。

通過調整 cp1X, cp1Y, cp2X, cp2Y 這四個控制點的值,可以改變貝塞爾曲線的形狀,從而控制數字增長的速度和加速度。 分段顯示數字的邏輯可以根據實際ui需求進行修改,例如可以根據不同的閾值進行分段,或者在不同的位置顯示數字片段。

記住在你的HTML文件中包含一個id為”count”的元素: 0

? 版權聲明
THE END
喜歡就支持一下吧
點贊14 分享