Pressumably,你想重新创建在以下网址显示的动画:https://developer.mozilla.org/en-US/docs/Web/SVG/Element/animateMotion
脱颖而出是你想添加的路径方式的第一件事。这不符合上述链接中显示的SVG。实际上,animateMotion元素不具有路径属性。它然而,是类型的子元素。
如果我调整生成的代码,使动画所需的所有元素 - 即圆圈,enimateMotion和mpath元素的路径,然后我生成看起来好的标记,虽然有一些(全部)自我 - 关闭标签被错误地表示为普通标签,尽管没有内容,但仅仅是属性。
但是,这个有点坏的SVG仍然无法使用!如果我然后清理并将“正常”标记更改为自动关闭标记,那么它工作正常。很明显,我也做错了什么。
首先,改性的javascript/HTML
window.addEventListener('load', onDocLoaded, false);
function onDocLoaded(evt)
{
var dom = byId('svg');
var path = document.createElementNS("http://www.w3.org/2000/svg","path");
path.setAttributeNS(null,"d","M10,110 A120,120 -45 0,1 110 10 A120,120 -45 0,1 10,110");
path.setAttributeNS(null,"stroke","lightgrey");
path.setAttributeNS(null,"stroke-width","2");
path.setAttributeNS(null,"fill","none");
path.setAttributeNS(null,"id","theMotionPath");
dom.appendChild(path);
// <path d="M10,110 A120,120 -45 0,1 110 10 A120,120 -45 0,1 10,110"
// stroke="lightgrey" stroke-width="2"
// fill="none" id="theMotionPath"/>
var circle=document.createElementNS("http://www.w3.org/2000/svg","circle");
circle.setAttributeNS(null,"cx",0);
circle.setAttributeNS(null,"cy",0);
circle.setAttributeNS(null,"r",5);
circle.setAttributeNS(null,"fill",'red');
var animateMotion=document.createElementNS("http://www.w3.org/2000/svg","animateMotion");
animateMotion.setAttributeNS(null,"dur",'6s');
animateMotion.setAttributeNS(null,"repeatCount",'indefinite');
// animateMotion.setAttributeNS(null,'path',path);
circle.appendChild(animateMotion);
var mPathObj = document.createElementNS("http://www.w3.org/2000/svg","mpath");
mPathObj.setAttribute("xlink:href",'#theMotionPath');
animateMotion.appendChild(mPathObj);
// <mpath xlink:href="#theMotionPath"/>
dom.appendChild(circle);
console.log(circle.appendChild,dom);
}
HTML
<body>
<svg id='svg' xmlns="http://www.w3.org/2000/svg" version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink">
</svg>
</body>
现在,所产生的(碎)SVG
<svg id="svg" xmlns="http://www.w3.org/2000/svg" version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink">
<path d="M10,110 A120,120 -45 0,1 110 10 A120,120 -45 0,1 10,110" stroke="lightgrey" stroke-width="2" fill="none" id="theMotionPath"></path><circle cx="0" cy="0" r="5" fill="red"><animateMotion dur="6s" repeatCount="indefinite"><mpath xlink:href="#theMotionPath"></mpath></animateMotion></circle></svg>
最后,工作之一:
<svg id="svg" xmlns="http://www.w3.org/2000/svg" version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink">
\t <path d="M10,110 A120,120 -45 0,1 110 10 A120,120 -45 0,1 10,110" stroke="lightgrey" stroke-width="2" fill="none" id="theMotionPath"/>
\t <circle cx="0" cy="0" r="5" fill="red">
\t \t <animateMotion dur="6s" repeatCount="indefinite">
\t \t \t <mpath xlink:href="#theMotionPath"/>
\t \t </animateMotion>
\t </circle>
</svg>
什么是代码中的'path'?如果我写'dom.appendChild(圆圈)',请提供一个[MCVE] – Kaiido
,这个控制台的圈子有animateMotion!但如果我补充一句,这个圈子没有孩子; – delen
使用您的确切代码,我得到一个animateMotion子项的圆圈。动画是否应该可视化工作并不是我们可以从您的代码中猜出来的,但是您确定该元素根本不存在吗?你使用IE吗? – Touffy