2016-02-25 38 views
0

我目前工作的SVG動畫。啓動Svg爲animateMotion jQuery的事件

我具有遵循與animateMotion屬性的路徑的SVG元素。

我的形狀:

<g id="dart" transform="scale(-1,1) translate(-587, -145)"> 
    <path d="..." /> 
</g> 

我的路徑:

<path id="motionPath" fill="none" stroke="none" stroke-miterlimit="10" d="..."/> 

我AnimateMotion:

<animateMotion xlink:href="#dart" dur="1s" begin="0s" fill="freeze" rotate="auto"><mpath xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#motionPath"></mpath></animateMotion> 

它完美。但是,當頁面加載後,它會在2s後開始移動。我想在JS活動上發佈動畫。事實上,我需要在頁面中向下滾動以查看SVG,並且當他可見時,動畫開始。

的JS:

var pos = $("#dart").offset().top; 
    $(window).scroll(function(){ 
      var scrollTop=$(window).scrollTop(); 
       if(scrollTop>=pos){ 
        /* --- start animation here with injecting --- */ 
         var motion=document.createElementNS("http://www.w3.org/2000/svg","animateMotion"); 
         motion.setAttributeNS("http://www.w3.org/1999/xlink", "xlink:href", "#dart"); 
         motion.setAttributeNS("http://www.w3.org/2000/svg", "dur", "1s"); 
         motion.setAttributeNS("http://www.w3.org/2000/svg", "begin", "0s"); 
         motion.setAttributeNS("http://www.w3.org/2000/svg", "fill", "freeze"); 
         motion.setAttributeNS("http://www.w3.org/2000/svg", "rotate", "auto"); 

         var mpath = document.createElementNS("http://www.w3.org/2000/svg","mpath"); 
         mpath.setAttributeNS("http://www.w3.org/1999/xlink", "xlink:href", "#motionPath"); 
         motion.appendChild(mpath); 
         document.getElementById("target").appendChild(motion); 
       } 
    }); 

我試圖注入(與createElementNS)的<animateMotion>或以啓動該事件的動畫來改變開始的值,但它不工作。

如果有人有一個想法......

回答

0

要總結一下我在評論中寫道originially ...

你通常通過設置例如開始屬性設置動畫運動開始就點擊begin="dart.click"

jQuery是設計的HTML工作,任何SVG的支持主要是出於偶然。所以當它創建元素時,它會在html命名空間而不是SVG命名空間中創建元素。因此,第一步是將代碼轉換爲使用標準DOM方法,如document.createElementNS。

如果你使用的DOM創建元素和屬性,照顧在正確的命名空間創建它們。

  • SVG元素應在SVG命名空間創建

  • 大多數屬性是空的命名空間,應通過調用element.setAttribute

  • XLink的設置:HREF屬性在xlink然而,必須通過調用element.setAttributeNS,通過XLink命名空間作爲第一個參數來創建命名空間。