javascript - SVG 动画 : Animate an arc as it is drawn

标签 javascript svg css-animations svg-animate

我正在使用以下代码段使用 SVG 绘制圆弧:

https://jsfiddle.net/e6dx9oza/293/

在调用describeArc方法计算路径时,会动态传入圆弧的起点和终点 Angular 。

有谁知道如何在绘制弧线时对其进行动画处理?基本上,我希望圆弧能够延迟平滑地绘制,而不是像本例那样一次性绘制。

最佳答案

你的问题没有描述你所说的“动画”是什么意思。下次提问时请考虑一下。

我假设您希望该扇区像扇形一样打开。

这是一种方法。

function polarToCartesian(centerX, centerY, radius, angleInDegrees) {
  var angleInRadians = (angleInDegrees-90) * Math.PI / 180.0;

  return {
    x: centerX + (radius * Math.cos(angleInRadians)),
    y: centerY + (radius * Math.sin(angleInRadians))
  };
}

function describeArc(x, y, radius, startAngle, endAngle){

    var start = polarToCartesian(x, y, radius, endAngle);
    var end = polarToCartesian(x, y, radius, startAngle);

    var arcSweep = endAngle - startAngle <= 180 ? "0" : "1";

    var d = [
        "M", start.x, start.y, 
        "A", radius, radius, 0, arcSweep, 0, end.x, end.y,
        "L", x,y,
        "L", start.x, start.y
    ].join(" ");
    
    //console.log(d);

    return d;       
}


function animateSector(x, y, radius, startAngle, endAngle, animationDuration) {

   var startTime = performance.now();

   function doAnimationStep() {
     // Get progress of animation (0 -> 1)
     var progress = Math.min((performance.now() - startTime) / animationDuration, 1.0);
     // Calculate the end angle for this point in the animation
     var angle = startAngle + progress * (endAngle - startAngle);
     // Calculate the sector shape
     var arc = describeArc(x, y, radius, startAngle, angle);
     // Update the path
     document.getElementById("arc1").setAttribute("d", arc);
     // If animation is not finished, then ask browser for another animation frame.
     if (progress < 1.0)
       requestAnimationFrame(doAnimationStep);
   }

   requestAnimationFrame(doAnimationStep);
}

animateSector(100, 100, 100, 120, 418.25, 1000); 
svg {
    height: 200px;
    width: 200px;
}
<svg>
  <path id="arc1" fill="green" />
</svg>

在这里 fiddle :https://jsfiddle.net/e6dx9oza/351/

关于javascript - SVG 动画 : Animate an arc as it is drawn,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49654966/

相关文章:

javascript - 在维护委托(delegate)事件的同时复制存储的 jQuery 对象

html - 使用宽度百分比时 CSS Typewriter 动画出错

javascript - 为什么我的 fadeslideshow 在 IE8 中不显示?

javascript - 使用 Dojo 获取查询字符串

android - SVG 无法在 Android Studio 中正确转换为具有高视口(viewport)的 XML Drawable

html - 网络图片的颜色可以与其背后的颜色相反吗?

animation - 如何减慢 Framer 动画速度

javascript - 如何使CSS动画按需向前或向后播放

javascript - 克隆div的特定内容并放入其他div

javascript - Canvas 库处理 SVG 的方式和 SVG 库处理 SVG 的方式有什么区别?