svg关于animateMotion动态改变path路径来控制svg元素移动

用js动态改变animateMotion的path属性 要控制移动的元素只有第一次的时候可以滑动,我用的定时器模拟的后台推过来的数据(用于控制元素移动的坐标)但是只能在第一次的时候可以滑动,然后调试发现path的值也改变了但是就是没有效果,以下是写的demo 请大家指点一下,困扰好长时间了,谢谢。PS:代码看着不清楚的 也可以到svgDemo看效果,浏览器中可以看到源码`<svg id="svg" width="800" height="750" viewBox="0 0 780 740" xmlns="http://www.w3.org/2000/svg&qu...

 <circle cx="50" cy="50" r="1" stroke="black"    stroke-width="1" fill="black"/>
 <circle cx="100" cy="100" r="1" stroke="black"    stroke-width="1" fill="black"/>
 <circle cx="150" cy="150" r="1" stroke="black"    stroke-width="1" fill="black"/>
 <circle cx="200" cy="200" r="1" stroke="black"    stroke-width="1" fill="black"/>
 <circle cx="250" cy="250" r="1" stroke="black"    stroke-width="1" fill="black"/>
 <circle cx="300" cy="300" r="1" stroke="black"    stroke-width="1" fill="black"/>
 <circle cx="350" cy="350" r="1" stroke="black"    stroke-width="1" fill="black"/>
 <circle cx="400" cy="400" r="1" stroke="black"    stroke-width="1" fill="black"/>
 <circle cx="450" cy="450" r="1" stroke="black"    stroke-width="1" fill="black"/>
 <circle cx="500" cy="500" r="1" stroke="black"    stroke-width="1" fill="black"/>
     
<!-- <path id="motionPath" fill="none" stroke="#000000" stroke-miterlimit="10" d="M 50,50 L 100,100"/> -->

<circle id="circle" r="10" cx="0" cy="0" fill="tomato" >

 <animateMotion
       id="animateMotion"
       xmlns:xlink="http://www.w3.org/1999/xlink"
       xlink:href="#circle"
       dur="2s"
       begin="0s"
       fill="freeze"
       repeatCount="1"> 
      <mpath xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#motionPath" />  
 </animateMotion>  

</circle>

<script type="text/javascript">

       <![CDATA[
            des = 50;    
            path=document.createElementNS("http://www.w3.org/2000/svg","path");
            path.setAttributeNS(null,"id","motionPath");
            path.setAttributeNS(null,"fill","none");
            path.setAttributeNS(null,"stroke","red");
            path.setAttributeNS(null,"stroke-miterlimit","10");
            path.setAttributeNS(null,"d","M 50,50 L 100,100");
            document.getElementById("svg").appendChild(path);
            
            setInterval("myInterval()",3000);
            function myInterval(){
                 var x1 = 50+des;
                 var y1 = 50+des;
                 var x2 = 100+des;
                 var y2 = 100+des;
                 p = "M " +x1+","+y1+" L "+x2+","+y2+"";
                 document.getElementById("motionPath").setAttribute("d",p);
                 if(des<401){
                      if(des==400){ 
                           des = 0;
                      }else{ 
                           des = des + 50;
                      }                 
                 }else{ 
                     des = 50;
                 }
            }
        ]]>

</script>
</svg> `

阅读 6.2k
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题