【问题标题】:CSS background image *.svg animated does not workingCSS 背景图像 *.svg 动画不起作用
【发布时间】:2025-12-28 10:45:12
【问题描述】:

我有动画 svg 文件,我想用它作为 div 的背景图片

div { background-image: url('anim.svg'); }

图像显示,但动画不起作用。

附:我不能在 html 中使用 svg-object,因为我有很多类似的对象,而且 svg-object 的代码也不短。

UPD:svg 文件代码:

    <?xml version="1.0" encoding="utf-8"?>
<svg height="69" width="62" class="hexagon" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
    <polygon points="30 0, 60 16, 60 50, 30 68, 0 50, 0 16" style="fill: none; stroke:#fff;stroke-width:1" />
    <polygon points="33 3, 33 3" style="fill: none; stroke:#fff;stroke-width:1">
        <animate attributeName="points" dur="500ms" to="33 3, 59 48" fill="freeze" />
    </polygon>
    <polygon points="28 2, 28 2" style="fill: none; stroke:#fff;stroke-width:1">
        <animate attributeName="points" dur="500ms" to="28 2, 0 49" fill="freeze" />
    </polygon>
    <polygon points="3 51, 3 51" style="fill: none; stroke:#fff;stroke-width:1">
        <animate attributeName="points" dur="500ms" to="3 51, 57 51" fill="freeze" />
    </polygon>
</svg> 

【问题讨论】:

  • 请将 anim.svg 的标记添加到问题中
  • 斯拉瓦,谢谢。有没有办法将 HTML 放入 svg 中?
  • 据我所知,您还不能将动画 SVG 用作实际图像。背景图像目前是一个不可动画的属性,因此它不起作用。希望我错了..这会很有趣。
  • 这应该可以工作,不幸的是 UA 还是有点问题。

标签: css html animation svg background


【解决方案1】:

您可以使用 svg:use 重复相似的对象,例如:

<svg>
  <defs>
    <g id="shape">
        <rect x="50" y="50" width="50" height="50" />
        <circle cx="50" cy="50" r="50" />
    </g>
  </defs>
</svg>

这段代码将渲染同一个对象:

<svg>
  <use xlink:href="#shape" x="200" y="50" />
</svg>

【讨论】: