简体   繁体   English

使用requestAnimationFrame重复的3秒动画

[英]3 sec animation that repeats with requestAnimationFrame

I have an SVG with an animation using requestAnimationFrame and the animation works but what I want it to do is animate over 3 secs and then repeat, so the animation for the circle will animate the dasharray and dashoffsset over 3seconds I don't know how to do this using css because it requires a calculation in javascript using Math.Pi can someone see if they can make this animation work the way I described. 我有一个使用requestAnimationFrame动画的SVG并且动画可以工作,但我想要它做的是动画超过3秒然后重复,所以圆圈的动画将动画dasharray和dashoffsset超过3秒我不知道如何使用css执行此操作,因为它需要使用Math.Pi在javascript中进行计算,有人可以看到他们是否可以按照我描述的方式使用此动画。 codepen.io codepen.io

HTML HTML

<svg width="20" height="20" viewBox="0 0 20 20">
  <circle cx="10" cy="10" r="7" fill="none" stroke="#e6e6e6" stroke-width="6" />
  <circle id="shape" cx="10" cy="10" r="7" fill="none" stroke="#ff0000" stroke-width="6" stroke-linecap="square" /> 
</svg>

CSS CSS

#shape {
 fill: none;
 stroke: red;
 stroke-width: 6;
 transition: all 4s ease-in-out;
 transform: rotate(-90deg);
 transform-origin: 50%;
}

JavaScript JavaScript的

var endPercentage = 100;

var shape = document.getElementById('shape');
var circumference = Math.PI * parseFloat(shape.getAttribute('r')) * 2;

shape.setAttribute('stroke-dasharray', circumference);
shape.setAttribute('stroke-dashoffset', circumference);

var updatePercentage = function () {
    var dashOffset = parseFloat(getComputedStyle(shape)['stroke-dashoffset']);
    var curPercentage = Math.floor((100 * (circumference - dashOffset)) / circumference) || 0;

    document.getElementById('perc').getElementsByClassName('value')[0].innerText = curPercentage;

    if (curPercentage < endPercentage) {
        window.requestAnimationFrame(updatePercentage);
    }
}

var animateShape = function (percent) {
    var offset = circumference - (circumference * percent / 100);
    shape.setAttribute('stroke-dashoffset', offset);
    window.requestAnimationFrame(updatePercentage);
}

setTimeout(function () {
    animateShape(endPercentage);
}, 0);

You can define pi with: 你可以用以下方法定义pi

:root {
  --PI: 3.14159265358979; 
}

...

stroke-dashoffset: calc(2 * var(--PI) * 7);
/* 7 is the radius of your circle */

With a combination of this and calc, you should be able to get a pure CSS solution. 结合使用this和calc,您应该能够获得纯CSS解决方案。

If you still want to go via the JS route, I recommend: 如果您仍想通过JS路线,我建议:

  shape.animate([
    { strokeDashoffset: 0 },
    { strokeDashoffset: circumference }
  ], { duration: 3000, iterations: Infinity });

Warning: polyfill required for older browsers. 警告:旧版浏览器需要填充多页填充。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM