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