2017-05-29 74 views
1

我把這個8形的循環當作SVG圖像。我感興趣的是動畫無限地沿着8循環動畫的白色50像素長度元素。是SVG行動畫上的元素

我明白SVG動畫是可以動畫繪製出來的,但是這個元素怎麼能夠緊跟SVG的行,這是否可能實現?用CSS實現這個更合理嗎?

這裏的元素應遵循的SVG路徑: enter image description here

這裏是一個要跨線動畫和循環使用SVG白元的視圖。 enter image description here

回答

1

我希望能夠正確地理解這個問題。

是的,這是可能的。

以下幾行代碼可以用作基礎。我只在Chrome測試,也許我把它寫在我的筆記本電腦的火車......

<!DOCTYPE html> 
 
<html lang="en"> 
 
<head> 
 
    <meta charset="UTF-8"> 
 
    <title>SVG 001</title> 
 
    <style> 
 
    body{font-family:"Calibri", sans-serif;} 
 
    svg{border:1px solid #eee;} 
 
    
 
    </style> 
 
</head> 
 
    <body> 
 
    <h1>Offset Dasharray</h1> 
 
    <svg id ="mySVG" width="500" height="500" viewBox="0 0 500 500"> 
 
    <path id="myPath" d="M 50 50 q 200 800 400 0" stroke="#ccc" 
 
    stroke-width="10" fill="none" /> 
 
    </svg> 
 
    <br> 
 
    <button onclick="dashAni(myPath, 50, 1500)">start</button> 
 
    <script> 
 
    var dashAni = function(path, length, duration){ 
 
     var dashPath = path.cloneNode(true); 
 
     mySVG.appendChild(dashPath); 
 
     var pathLen=path.getTotalLength(); 
 
     var aktPos=0 
 
     var sumSteps = duration/(1000/60) // 60 pics per second 
 
     var step=0; 
 
     var pathAnim; 
 
     dashPath.setAttribute('stroke-dasharray', length + ' ' + (pathLen - length)); 
 
     dashPath.setAttribute('stroke', "red"); 
 
     dashPath.setAttribute('stroke-dashoffset', aktPos); 
 

 
     var anim=function(){ 
 
     aktPos = pathLen/sumSteps*step*-1; 
 
      //aktLen = easeInOutQuad(step/sumSteps)*len; 
 
     dashPath.setAttribute('stroke-dasharray', length + ' ' + pathLen); 
 
     dashPath.setAttribute('stroke-dashoffset', aktPos); 
 

 
     if (step <= (sumSteps)){ 
 
      step++; 
 
      pathAnim = setTimeout(anim, 1000/60) //1000/60 pics/second 
 
      } else { 
 
      mySVG.removeChild(dashPath); 
 
      clearTimeout(pathAnim); 
 
      } 
 
     } 
 
    anim(); 
 
    } 
 
    dashAni(myPath, 50, 1500); 
 
    </script> 
 
</body> 
 
</html>

+0

你的答案引導我在正確的方向。雖然我仍然無法實現沿着svg的白色動畫線:https://jsfiddle.net/yrj7htoy/2/。你可以請建議這個代碼? – user3615851

+0

我認爲問題是你有不連續的路徑。當你使用多個「m」時,路徑被破壞... –

+0

我已關閉我的路徑: [fiddle](https://jsfiddle.net/pa9ubf2a/) –