使用“请求动画帧”更改画布动画的持续时间

时间:2016-08-29 04:17:59

标签: animation canvas requestanimationframe

我正在尝试设置一个类似于进度条的圆形动画。我打算在旋转木马上使用它来跟踪下一张幻灯片何时出现。我遇到的问题是我不知道如何更改动画的持续时间。我尝试调整帧率,它可以工作,但动画变得非常不稳定。 setInterval类似的工作,但它显示整个圆而不仅仅是我想要的一部分,所以我无法正确计时。我需要能够控制动画的速度,减慢它的速度,而不是它。我正在处理的代码如下。

<script>    
    (function() {
        var requestAnimationFrame = window.requestAnimationFrame || 
                                    window.mozRequestAnimationFrame ||
                                    window.webkitRequestAnimationFrame || 
                                    window.msRequestAnimationFrame;
                                    window.requestAnimationFrame = requestAnimationFrame;
    })();
        var canvas = document.getElementById('myCanvas');
        var context = canvas.getContext('2d');
        var centerX = canvas.width / 2;
        var centerY = canvas.height / 2;
        var radius = 90;
        var endPercent = 85;
        var curPerc = 0;
        var circ = -Math.PI;
        var quart = -(Math.PI * 2) + 1;

        function animate(current) {
            context.clearRect(0, 0, canvas.width, canvas.height);
            context.beginPath();
            context.arc(centerX, centerY, radius, -(quart), ((circ) * current) - quart, true);
            context.lineWidth = 3;
            context.strokeStyle = '#000';
            context.stroke();
            curPerc++;
            if (curPerc < endPercent) {
                requestAnimationFrame(function () {
                animate(curPerc / 100)
                });
            }
        }

     animate();
</script>

1 个答案:

答案 0 :(得分:4)

requestAnimationFrame确实在回调参数中传递了高分辨率时间戳。因此,您可以使用它来确定当前动画的位置,并使用此增量时间来设置位置变量,而不是curPerc++

这是一个天真的实现。

var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var centerX = canvas.width / 2;
var centerY = canvas.height / 2;
var radius = 90;
var endPercent = 85;
var quart = -(Math.PI * 2) + 1;
var startTime = null;
var duration = null;

function animate(time) {

  if (!startTime) {
    startTime = time;
  }

  var delta = Math.min(1, (time - startTime) / duration);
  var curPerc = ((-2 * Math.PI) / 100) * (endPercent * delta);

  context.clearRect(0, 0, canvas.width, canvas.height);
  context.beginPath();
  context.arc(centerX, centerY, radius, -quart, curPerc - quart, true);
  context.stroke();

  if (delta < 1) {
    requestAnimationFrame(animate);
  } else {
    startTime = null;
    slider.disabled = false;
  }
}

var startAnim = function() {
  context.lineWidth = 3;
  context.strokeStyle = '#000';

  slider.disabled = true;
  duration = +slider.value;
  l.textContent = duration + 'ms';
  requestAnimationFrame(animate);
};
slider.onchange = startAnim;
startAnim();
<p>use the slider to update the animation's duration</p>
<input type="range" min="250" max="9000" value="2000"id="slider" />
<label id="l"></label><br>
<canvas id="myCanvas" height="300"></canvas>