使用XHTML中的嵌入式SVG从Javascript创建动画

时间:2012-05-07 18:14:23

标签: javascript dom animation xhtml svg

我在XHTML中使用嵌入式SVG并希望从Javascript创建动画,但它无法按预期工作

我使用XPDL为业务流程建模,并将模拟连接到我使用javascript动画的SVG图形。我在Firefox中这样做,模型和图形嵌入在XHTML中。现在问题是我想使用animateMotion-Tag沿路径移动对象。两者都已存在,所以我尝试将我的解决方案写入SVG文件,这很好用。看起来像是:

<animateMotion xlink:href="#id1" rotate="auto" dur="2s">
    <mpath xlink:href="#id2">
</animateMotion>

当然,命名空间设置正确,因此按预期工作。我手动触发它,因此不需要开始时间。现在,我在现有的混合XHTML / SVG-dom中做同样事情的方法:

function moveAlongPath(elemId,pathId,rotate,duration)
{
  var svgNs = "http://www.w3.org/2000/svg";
  var xlinkNs = "http://www.w3.org/1999/xlink";
  var motionElem = document.createElementNS(svgNs,"animateMotion");
  motionElem.setAttributeNS(xlinkNs,"href","#" + elemId);
  motionElem.setAttributeNS(svgNs,"rotate",rotate);
  motionElem.setAttributeNS(svgNs,"dur",duration + "ms");
  var pathRef = document.createElementNS(svgNs,"mpath");
  pathRef.setAttributeNS(xlinkNs,"href","#" + pathId);
  motionElem.appendChild(pathRef);
  var animElem = svgRootNode.getElementById(elemId); // It is indeed the <svg>-Node
  animElem.appendChild(motionElem);
  // Setting x and y to 0 is important for the Element to be "on" the Path
  animElem.setAttribute("x",0);
  animElem.setAttribute("y",0);
  motionElem.beginElement();
}

当我在firebug中检查dom时,这似乎产生了具有相同属性的相同节点结构,虽然href不是以xlink:为前缀,但setAttributeNS应该这样做,对吧?这里的问题是我无法用beginElement()启动动画。这里什么都没发生。

我希望那里有帮助,我现在非常绝望。

编辑: 我终于找到了它。当我使用

时,问题就消失了
setAttributeNS(null,"attr",value)

而不是

setAttributeNS(svgNs,"attr",value)

如果我错了,请纠正这个问题,但这不是我认为XML的第一种方法吗?那应该没有无命名空格的属性?无论如何 - 已解决!

2 个答案:

答案 0 :(得分:0)

使用

setAttributeNS(null,"attr",value)

而不是

setAttributeNS(svgNs,"attr",value)

答案 1 :(得分:0)

variableElementNS.href.baseVal = value;