我想在一条线上移动一个圆圈,比如说3秒后。我正在使用JS动态绘制一个圆,并将它和setTimeout进行时间延迟。当我加载页面时,圆圈在3秒后出现,但同时在行上走了一段距离(它应该从行的开头开始,即(30,y1))。我不知道我哪里出了问题。以下是相关代码:
train.js
function RunTrain(x,y,desti,time,r)
{
var xmlns="http://www.w3.org/2000/svg";
var C=document.createElementNS(xmlns,"circle");
C.setAttributeNS(null,"cx",x);
C.setAttributeNS(null,"cy",y);
C.setAttributeNS(null,"r",r);
C.setAttribute("style","stroke-width:1;stroke:blue;fill:skyblue");
var animate=document.createElementNS(xmlns,"animate");
animate.setAttribute("attributeName","cx");
animate.setAttribute("attributeType","XML");
animate.setAttribute("from",x);
animate.setAttribute("to",desti);
animate.setAttribute("dur","2s");
animate.setAttribute("begin","0s");
animate.setAttribute("repeatCount","1");
animate.setAttribute("fill","freeze");
C.appendChild(animate);
document.getElementById("id1").appendChild(C);
//id1 is the id of svg tag
}
call.js
setTimeout(function(){ RunTrain(30,y1,Mlx2,5,10); },3000);
demo.html
<svg height = 5000 width = 5000 id="id1"> </svg>
<script src="/static/train.js"></script>
<script src="/static/call.js"></script>
注:这是django项目的一部分。我在用莫兹拉。
编辑
这个animateTransform甚至在调用beginElement时也会造成麻烦。
var animateTransform=document.createElementNS(xmlns,"animateTransform");
animateTransform.setAttribute("attributeName","transform");
animateTransform.setAttribute("attributeType","scale");
animateTransform.setAttribute("dur","2s");
animateTransform.setAttribute("begin","3s");
animateTransform.setAttribute("from","0 0");
animateTransform.setAttribute("to","160 "+ y1);
animateTransform.setAttribute("fill","freeze");
发布于 2016-10-28 06:15:05
SMIL动画的动画定时器在创建SVG文档时开始挠痒。因此,如果您说是begin="0s"
,这意味着动画应该在文档第一次创建时启动。在您的示例中,这是将<svg>
添加到DOM中的时候。当您在3秒后添加<circle>
和<animate>
元素时,就不会了。所以动画就开始了,就好像你已经跑了3秒。
代码最简单的修复方法是设置begin="indefinite"
并在添加元素之后启动动画。您可以通过调用beginElement()
来做到这一点。请参阅下面的演示。
function RunTrain(x,y,desti,time,r)
{
var xmlns="http://www.w3.org/2000/svg";
var C=document.createElementNS(xmlns,"circle");
C.setAttributeNS(null,"cx",x);
C.setAttributeNS(null,"cy",y);
C.setAttributeNS(null,"r",r);
C.setAttribute("style","stroke-width:1;stroke:blue;fill:skyblue");
var animate=document.createElementNS(xmlns,"animate");
animate.setAttribute("attributeName","cx");
animate.setAttribute("attributeType","XML");
animate.setAttribute("from",x);
animate.setAttribute("to",desti);
animate.setAttribute("dur",time);
animate.setAttribute("begin","indefinite");
animate.setAttribute("repeatCount","1");
animate.setAttribute("fill","freeze");
C.appendChild(animate);
document.getElementById("id1").appendChild(C);
//id1 is the id of svg tag
animate.beginElement();
}
var y1 = 30;
var Mlx2 = 400;
setTimeout(function(){ RunTrain(30,y1,Mlx2,5,10); },3000);
<svg height="5000" width="5000" id="id1"></svg>
https://stackoverflow.com/questions/40282232
复制相似问题