【问题标题】:How to apply the same animation to several SVG objects如何将相同的动画应用于多个 SVG 对象
【发布时间】:2011-10-19 09:27:36
【问题描述】:

我想在嵌入式 SVG 中创建一个柱形图,在每列的鼠标悬停事件上具有简单的彩色动画效果。如何只创建一次动画并将其应用于任何列?

在下面的示例中,我将彩色动画放在第一列。具体问题是如何在不重复节点的情况下在其他列(节点)上应用相同的动画。我应该使用 JavaScript 吗?或者我可以在动画节点上使用某种引用吗?

<svg class="columnChart">
    <g transform="matrix(1 0 0 -1 0 0) translate(0, -100)">
        <rect width="10" height="100" x="0" y="0">
            <animate attributeName="fill"
                attributeType="XML"
                begin="mouseover"
                dur="0.25s"
                fill="freeze"
                to="#00ff00"/>
            <animate attributeName="fill"
                attributeType="XML"
                begin="mouseout"
                dur="0.25s"
                fill="freeze"
                to="#000000"/>
        </rect>
        <rect width="10" height="80" x="15" y="0"/>
        <rect width="10" height="55" x="30" y="0"/>
        <rect width="10" height="60" x="45" y="0"/>
    </g>
    <g transform="rotate(90)">
        <text x="110">mo</text>
    </g>
    <g transform="rotate(90)">
        <text x="110" y="-15">tu</text>
    </g>
    <g transform="rotate(90)">
        <text x="110" y="-30">we</text>
    </g>
    <g transform="rotate(90)">
        <text x="110" y="-45">th</text>
    </g>
</svg>

提前感谢您的帮助。

【问题讨论】:

    标签: javascript html animation svg


    【解决方案1】:

    很遗憾,您不能重复使用动画元素。所以是的,您应该以两种方式之一使用 Javascript。您可以使用它来复制动画元素并将它们添加到每个元素中,或者直接在 JS 中制作动画(这可能会更好)。

    【讨论】:

      【解决方案2】:

      您可以通过定义来做到这一点。在我的情况下,我重新使用动画渐变作为填充。使用相关动画定义填充(例如使用 id animating_fill),然后使用 style="...fill:url(#animating_fill);..." 将其作为条中的填充引用。

      我认为这可能比 js 解决方案更好(尽管在我的案例中我确实使用 JS 来设置定义)。

      【讨论】:

        【解决方案3】:

        您可以使用CSS3 Transitions。这是一个 example,它结合了 SVG 动画和 CSS 过渡,不透明度使用 CSS 过渡动画,矩形宽度使用 &lt;animate&gt; 元素。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-01-28
          • 1970-01-01
          • 2020-03-29
          • 2020-08-23
          相关资源
          最近更新 更多