计算从A到B的动画

时间:2013-06-08 00:09:59

标签: javascript

我正在通过间隔numeric value更新element内的ajax requests

为了使整个事物更活跃,我希望从current值到new值计算,部分在 - 或减少 {{ 1}}在value的时间内。

所以基本上是这样的:

n sec

是否有这样的javascript库?

10 个答案:

答案 0 :(得分:49)

您可以自己编写简单的代码:

function animateValue(id, start, end, duration) {
    var range = end - start;
    var current = start;
    var increment = end > start? 1 : -1;
    var stepTime = Math.abs(Math.floor(duration / range));
    var obj = document.getElementById(id);
    var timer = setInterval(function() {
        current += increment;
        obj.innerHTML = current;
        if (current == end) {
            clearInterval(timer);
        }
    }, stepTime);
}

animateValue("value", 100, 25, 5000);
#value {
    font-size: 50px;
}
<div id="value">100</div>


这是一个更准确的版本,如果定时器间隔不完全准确(有时它们不是),则自我调整:

function animateValue(id, start, end, duration) {
    // assumes integer values for start and end
    
    var obj = document.getElementById(id);
    var range = end - start;
    // no timer shorter than 50ms (not really visible any way)
    var minTimer = 50;
    // calc step time to show all interediate values
    var stepTime = Math.abs(Math.floor(duration / range));
    
    // never go below minTimer
    stepTime = Math.max(stepTime, minTimer);
    
    // get current time and calculate desired end time
    var startTime = new Date().getTime();
    var endTime = startTime + duration;
    var timer;
  
    function run() {
        var now = new Date().getTime();
        var remaining = Math.max((endTime - now) / duration, 0);
        var value = Math.round(end - (remaining * range));
        obj.innerHTML = value;
        if (value == end) {
            clearInterval(timer);
        }
    }
    
    timer = setInterval(run, stepTime);
    run();
}

animateValue("value", 100, 25, 5000);
#value {
    font-size: 50px;
}
<div id="value">100</div>

答案 1 :(得分:10)

当前的解决方案确实比需要的更新次数更多。这是一种基于帧的方法,很准确:

function animateValue(obj, start, end, duration) {
  let startTimestamp = null;
  const step = (timestamp) => {
    if (!startTimestamp) startTimestamp = timestamp;
    const progress = Math.min((timestamp - startTimestamp) / duration, 1);
    obj.innerHTML = Math.floor(progress * (end - start) + start);
    if (progress < 1) {
      window.requestAnimationFrame(step);
    }
  };
  window.requestAnimationFrame(step);
}

const obj = document.getElementById('value');
animateValue(obj, 100, -25, 2000);
div {font-size: 50px;}
<div id="value">100</div>

答案 2 :(得分:3)

我对这种动画略有不同。基于这些假设:

  1. 有一个起始文字(作为非JS浏览器或Google的后备 索引)
  2. 此文本可以包含非数字字符
  3. 该函数直接将元素 用作第一个参数(与 元素ID)

因此,如果您要为“ + 300%毛利”这样的简单文本设置动画,则只会对数字部分进行动画处理。

此外,所有参数现在都具有startendduration的默认值。

https://codepen.io/lucamurante/pen/gZVymW

function animateValue(obj, start = 0, end = null, duration = 3000) {
    if (obj) {

        // save starting text for later (and as a fallback text if JS not running and/or google)
        var textStarting = obj.innerHTML;

        // remove non-numeric from starting text if not specified
        end = end || parseInt(textStarting.replace(/\D/g, ""));

        var range = end - start;

        // no timer shorter than 50ms (not really visible any way)
        var minTimer = 50;

        // calc step time to show all interediate values
        var stepTime = Math.abs(Math.floor(duration / range));

        // never go below minTimer
        stepTime = Math.max(stepTime, minTimer);

        // get current time and calculate desired end time
        var startTime = new Date().getTime();
        var endTime = startTime + duration;
        var timer;

        function run() {
            var now = new Date().getTime();
            var remaining = Math.max((endTime - now) / duration, 0);
            var value = Math.round(end - (remaining * range));
            // replace numeric digits only in the original string
            obj.innerHTML = textStarting.replace(/([0-9]+)/g, value);
            if (value == end) {
                clearInterval(timer);
            }
        }

        timer = setInterval(run, stepTime);
        run();
    }
}

animateValue(document.getElementById('value'));
#value {
    font-size: 50px;
}
<div id="value">+300% gross margin</div>

答案 3 :(得分:2)

这很有效。但是,我需要在数字中使用逗号。以下是检查逗号的更新代码。希望有人发现这有用,如果他们偶然发现这篇文章。

function animateValue(id, start, end, duration) {

    // check for commas
    var isComma = /[0-9]+,[0-9]+/.test(end); 
    end = end.replace(/,/g, '');

    // assumes integer values for start and end

    var obj = document.getElementById(id);
    var range = end - start;
    // no timer shorter than 50ms (not really visible any way)
    var minTimer = 50;
    // calc step time to show all interediate values
    var stepTime = Math.abs(Math.floor(duration / range));

    // never go below minTimer
    stepTime = Math.max(stepTime, minTimer);

    // get current time and calculate desired end time
    var startTime = new Date().getTime();
    var endTime = startTime + duration;
    var timer;

    function run() {
        var now = new Date().getTime();
        var remaining = Math.max((endTime - now) / duration, 0);
        var value = Math.round(end - (remaining * range));
        obj.innerHTML = value;
        if (value == end) {
            clearInterval(timer);
        }
        // Preserve commas if input had commas
        if (isComma) {
            while (/(\d+)(\d{3})/.test(value.toString())) {
                value = value.toString().replace(/(\d+)(\d{3})/, '$1'+','+'$2');
            }
        }
    }

    var timer = setInterval(run, stepTime);
    run();
}

animateValue("value", 100, 25, 2000); 

答案 4 :(得分:1)

现在我们可以使用 CSS 变量和新的 @property 为计数器(以及许多以前无法动画的东西)设置动画。 不需要 javascript。目前supports只有 Chrome 和 Edge。

@property --n {
  syntax: "<integer>";
  initial-value: 0;
  inherits: false;
}

body {
  display: flex;
}

.number {
  animation: animate var(--duration) forwards var(--timing, linear);
  counter-reset: num var(--n);
  font-weight: bold;
  font-size: 3rem;
  font-family: sans-serif;
  padding: 2rem;
}
.number::before {
  content: counter(num);
}

@keyframes animate {
  from {
    --n: var(--from);
  }
  to {
    --n: var(--to);
  }
}
<div class="number" style="--from: 0; --to: 100; --duration: 2s;"></div>
<div class="number" style="--from: 10; --to: 75; --duration: 5s; --timing: ease-in-out"></div>
<div class="number" style="--from: 100; --to: 0; --duration: 5s; --timing: ease"></div>

答案 5 :(得分:0)

HTML

<!DOCTYPE html>
<html>
<head>
    <title>Count</title>
</head>
<body>
    <div id="value">1000</div>
</body>
</html>

JAVASCRIPT代码段

这是一个简单的js函数,将给定起始编号的值递减为结束编号(对象原型)。

function getCounter(startCount,endcount,time,html){
objects = {
    //you can alternateif you want yo add till you reach the endcount
    startCount:startCount,
    endCount:endcount,
    timer:time
}
this.function = function(){
    let startTm  = objects.startCount,
        timer = objects.timer,
        endCount = objects.endCount;
        //if you want it to add a number just replace the -1 with +1
        /*and dont forget to change the values in the object prototype given a variable of counter*/
    let increament = startTm  < endCount ? 1:-1;
        timmer  = setInterval(function(){
                startTm  += increament;
                html.innerHTML = startTm ;
                if(startTm  == endCount){
                    clearInterval(timmer);
                }
            },timer);
   }
}
// input your startCount,endCount  the timer.....
let doc = document.getElementById('value');

let counter = new getCounter(1000,1,10,doc);
//calling the function in the object
counter.function();

查看此演示https://jsfiddle.net/NevilPaul2/LLk0bzvm/

答案 6 :(得分:0)

这是我想出的:

function animateVal(obj, start=0, end=100, steps=100, duration=500) {   
    start = parseFloat(start)
    end = parseFloat(end)

    let stepsize = (end - start) / steps
    let current = start
    var stepTime = Math.abs(Math.floor(duration / (end - start)));
    let stepspassed = 0
    let stepsneeded = (end - start) / stepsize

    let x = setInterval( () => {
            current += stepsize
            stepspassed++
            obj.innerHTML = Math.round(current * 1000) / 1000 
        if (stepspassed >= stepsneeded) {
            clearInterval(x)
        }
    }, stepTime)
}   

animateVal(document.getElementById("counter"), 0, 200, 300, 200)

答案 7 :(得分:0)

这里是一个版本,其中增量按定义的乘数(mul)增长。 frameDelay是每个增量的时间延迟。如果您的值camn

function cAnimate(id, start, end, frameDelay = 100, mul = 1.2) {
    var obj = document.getElementById(id);
    var increment = 2;
    var current = start;
    var timer = setInterval(function() {
        current += increment;
        increment *= mul;
        if (current >= end) {
            current = end;
            clearInterval(timer);
        }

        obj.innerHTML = Math.floor(current).toLocaleString();

    }, frameDelay);
}

cAnimate("counter", 1, 260000, 50);

答案 8 :(得分:0)

我将所有这些混合使用来创建一个更新BehaviorSubject的函数。

function animateValue(subject, timerRef, startValue, endValue, duration){
  if (timerRef) {  clearInterval(timerRef); }
  const minInterval = 100;
  const valueRange = endValue - startValue;
  const startTime = new Date().getTime();
  const endTime = startTime + (duration * 1000);
  const interval = Math.max((endTime-startTime)/valueRange, minInterval);

  function run() {
    const now = new Date().getTime();
    const rangePercent = Math.min(1-((endTime-now)/(endTime-startTime)),1);
    const value = Math.round(rangePercent * valueRange+startValue);

    subject.next(value);
    if (rangePercent >= 1) {
      clearInterval(timerRef);
    }
  }

  timerRef = setInterval(run, interval);
  run();
}

答案 9 :(得分:0)

const counters = document.querySelectorAll('.counters');

counters.forEach(counter => {
  let count = 0;
  const updateCounter = () => {
    const countTarget = parseInt(counter.getAttribute('data-counttarget'));
    count++;
    if (count < countTarget) {
      counter.innerHTML = count;
      setTimeout(updateCounter, 1);
    } else {
      counter.innerHTML = countTarget;
    }
  };
  updateCounter();
});
<p class="counters" data-counttarget="50"></p>
<p class="counters" data-counttarget="100"></p>
<p class="counters" data-counttarget="500"></p>
<p class="counters" data-counttarget="1000"></p>