【发布时间】:2016-08-29 13:22:53
【问题描述】:
我正在尝试制作一个类似于进度条的圆形动画。我打算在轮播中使用它来跟踪下一张幻灯片何时出现。我遇到的问题是我不知道如何更改动画的持续时间。我尝试调整帧速率,它可以工作,但动画变得非常不稳定。 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>
【问题讨论】:
-
这是一个 good article 和 github gist 伴随它,基于时间的画布动画。
标签: animation canvas requestanimationframe