Search code examples
animationsvggeometrygeometric-arc

Define a circle / arc animation in SVG


Does anyone know how to define an animated arc / circle in SVG, such that the arc starts at 0 degrees and ends at 360 degrees?


Solution

  • you can paint it "by hand" using path's lineto and calculate the position of the arc:

    <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1"
       viewBox="0 0 1200 800"
       preserveAspectRatio="xMidYMid"
       style="width:100%; height:100%; position:absolute; top:0; left:0;"
       onload="drawCircle();"> 
      <script> 
        function drawCircle() {
            var i = 0;
            var circle = document.getElementById("arc");
            var angle = 0;
            var radius = 100;     
            window.timer = window.setInterval(
            function() {
                angle -=5;  
                angle %= 360;
                var radians= (angle/180) * Math.PI;
                var x = 200 + Math.cos(radians) * radius;
                var y = 200 + Math.sin(radians) * radius;
                var e = circle.getAttribute("d");
                if(i==0) {
                    var d = e+ " M "+x + " " + y;
                }
                else {
                    var d = e+ " L "+x + " " + y;
                }
                if (angle === -5 && i !== 0) {
                    window.clearInterval(window.timer);
                }
    
                circle.setAttribute("d", d);
                i++;
            } 
          ,10)
        }
        </script> 
    
        <path d="M200,200 " id="arc" fill="none" stroke="blue" stroke-width="2" />
    </svg>
    

    http://jsfiddle.net/k99jy/138/