svg圈子路径动画

时间:2017-06-04 08:51:57

标签: javascript svg

我想用SVG创建一个动画,这里有一些问题。 小圆圈应沿大圆的路径移动。 有人可以通过一些提示或一个简单的例子向我展示方式吗? 我用css试过了,但这不是正确的方法。

<!doctype html>
<html lang="en">
<head>
</head>
<body>
  <svg>
    <circle id="c1" cx="100" cy="100" r="90" stroke="#ccc" stroke-width="2" fill="none"/>
    <circle id ="c2" cx="100" cy="10" r="8" stroke="#f00" stroke-width="3" fill="#fff"/> 
  </svg>
  <script>
    circle1=document.getElementById("c1");
    circle2=document.getElementById("c2");

    for (i=1;i<60;i++){
      // here is must calc the points 
      //of the path of the circle
      //that is difficult but not such a problem
      //but i don´t see an animation
      //but I see no animation
      circle2.setAttribute("cx",100+i);
      circle2.setAttribute("cy",100+i);
    }  
  </script>
</body>
</html>    

1 个答案:

答案 0 :(得分:0)

美好的一天,欢迎,

我认为计算圆点的方法太精细了。使用变换旋转更容易旋转圆圈。

上周我在研讨会上回答了类似的问题如下:

(请仔细阅读以及备注。我希望您理解代码。)

<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>
<body>
  <svg id = "mySVG" width="200" height="200" viewBox="0 0 200 200">
    <circle id = "myCirclePath" cx="100" cy="100" r="90" stroke="#ccc" stroke-width="2" fill="none"/>
    <circle id = "myAniCircle" cx="100" cy="10" r="8" stroke="#f00" stroke-width="3" fill="#fff"/> 
  </svg>
  <script>
    var animateAtCircle = function (elementToAnimate, circlePath, duration, callback){
      //I would see:
      var imagesPerSecond = 60;
      //and calculate the sum of steps i need:
      var sumSteps = duration / (1000/imagesPerSecond);
      //an circle has 360 degrees
      //so my stepwidth is:
      var stepWidth = 360 / sumSteps
      //let us begin with step 1
      var step = 1;
      //before, i need a Variable to store my Timeout
      var pathAnim;
      //and begin with our animation function
      var anim=function(){
        //rotate the circle relative
        //to the midpoint of circlePath
        elementToAnimate.setAttribute("transform",`rotate(
          ${step*stepWidth},
          ${circlePath.getAttribute('cx')},
          ${circlePath.getAttribute('cy')}
          )`);
        //until step smaller then sumSteps
        if ( step < sumSteps){
          //set step to next step
          step ++
          //and wait for creating next rotation an call anim again...
          pathAnim = setTimeout(anim, 1000/imagesPerSecond);
        } else {
          //animation is finished;
          clearTimeout(pathAnim);
          //call callback function
          if (callback) return callback();
        }
      }
      //now call our anim loop function
      anim();
    }
    //now call our Aimation at circle...
    animateAtCircle(myAniCircle,myCirclePath,5000, function(){console.log('finished');});
  </script>
</body>
</html>