SVG 动画:绘制弧线时对其进行动画处理

Ama*_*ony 1 javascript svg css-animations svg-animate

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

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

describeArc当调用方法计算路径时,将动态输入圆弧的起始和结束角度。

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

Pau*_*eau 5

You question doesn't describe what you mean by "animate". Please think about that next time you ask a question.

I am going to assume you want the sector to open like a fan.

Here's one way to do it.

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); 
Run Code Online (Sandbox Code Playgroud)
svg {
    height: 200px;
    width: 200px;
}
Run Code Online (Sandbox Code Playgroud)
<svg>
  <path id="arc1" fill="green" />
</svg>
Run Code Online (Sandbox Code Playgroud)

Fiddle here: https://jsfiddle.net/e6dx9oza/351/