【问题标题】:SVG – animate rectangle along path; center of rect always on the pathSVG – 沿路径动画矩形;矩形的中心始终在路径上
【发布时间】:2012-10-28 05:01:36
【问题描述】:

我想为一个矩形设置动画,使其遵循迄今为止使用animateMotion 工作的给定路径。这就是我得到的:

<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 提供的方式实现吗?

【问题讨论】:

    标签: svg svg-animate


    【解决方案1】:

    当然,只需在矩形中添加一个变换即可。

    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>

    translate 将矩形原点从 0,0 移动到矩形中心。

    【讨论】:

    • 如果您只需在工作解决方案中添加一个指向活跃小提琴的链接,您的答案会多么酷。
    • 成功了,谢谢。但为什么?我知道translate 部分通常会做什么,但不明白为什么它在这种情况下起作用并且做了我打算做的事情。
    • @RobertLongson 怎么会这样?您的回复似乎说明了一点,您收到了建议不要添加小提琴链接的反馈,对吗?如果是这样的话,听起来很奇怪......
    • @MorganWilde 它现在是一个堆栈 sn-p 所以它会在这里运行。
    猜你喜欢
    • 2016-11-27
    • 1970-01-01
    • 2018-04-20
    • 2014-02-18
    • 1970-01-01
    • 2022-01-22
    • 1970-01-01
    • 2022-10-26
    • 1970-01-01
    相关资源
    最近更新 更多