【问题标题】:3 sec animation that repeats with requestAnimationFrame使用 requestAnimationFrame 重复的 3 秒动画
【发布时间】:2019-08-27 20:36:31
【问题描述】:

我有一个带有动画的 SVG,使用 requestAnimationFrame 并且动画有效,但我想要它做的是动画超过 3 秒,然后重复,所以圆圈的动画将动画 dasharray 和 dashoffsset 超过 3 秒我不知道如何使用 css 执行此操作,因为它需要使用 Math.Pi 在 javascript 中进行计算,有人可以看看他们是否可以让这个动画按照我描述的方式工作。 codepen.io

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

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

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);

【问题讨论】:

    标签: javascript jquery css


    【解决方案1】:

    你可以定义pi

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

    结合 this 和 calc,你应该可以得到一个纯 CSS 的解决方案。

    如果你还想走JS路线,我推荐:

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

    警告:旧版浏览器需要 polyfill。

    【讨论】:

      猜你喜欢
      • 2023-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-08
      • 2015-01-14
      • 1970-01-01
      • 2015-01-04
      • 2014-07-20
      相关资源
      最近更新 更多