2012-11-08 146 views
3

我想動畫一個矩形,以便它遵循給定的路徑,迄今爲止使用animateMotion工作。這是我有:SVG - 沿着路徑的動畫矩形;矩形中心總是在路徑上

<svg xmlns="http://www.w3.org/2000/svg" version="1.1"> 
<g> 
    <rect height="40" width="40" style="fill:#777; stroke:none;"/> 
    <animateMotion fill="freeze" path="M 0 0 Q 190 160 150 70 T 200 150 T 300 200 T 200 200" dur="3.14159s" repeatCount="indefinite"/> 
</g> 
<path d="M 0 0 Q 190 160 150 70 T 200 150 T 300 200 T 200 200" style="fill:none;stroke:#F00;stroke-width:5"/> 

現在我的問題:我如何讓矩形遵循的路徑(已實現)與矩形(20 20)的中心始終是路徑上?這可以通過SVG提供的方式來實現嗎?

回答

3

當然,只需要向rect添加一個轉換即可。

html, body, svg { 
 
    height: 100%; 
 
    width: 100%; 
 
}
<svg> 
 
    <g> 
 
     <rect transform="translate(-20,-20)" height="40" width="40" style="fill:#777; stroke:none;"/> 
 
     <animateMotion fill="freeze" path="M 0 0 Q 190 160 150 70 T 200 150 T 300 200 T 200 200" dur="3.14159s" repeatCount="indefinite"/> 
 
    </g> 
 
    <path d="M 0 0 Q 190 160 150 70 T 200 150 T 300 200 T 200 200" style="fill:none;stroke:#F00;stroke-width:5"/> 
 
</svg>

從0,0移動RECT原點到矩形中心的翻譯行爲。

+0

如果您只是將工作解決方案的鏈接添加到活動小提琴中,您的答案會有多酷。 –

+0

它的工作,謝謝。但爲什麼?我知道'translate'部分通常會做什麼,但不明白爲什麼它在這種情況下起作用,並且做我想做的事情。 – PattaFeuFeu

+0

@RobertLongson怎麼樣?您的回覆似乎有一點重要,您已收到反饋意見,建議不要添加小提琴鏈接,是嗎?聽起來相當怪異,如果是這樣的話...... –