SVG:<使用>元素嵌套在g中时不起作用(带小提琴!

SVG: <use> element not working when nested in g (with fiddle!)

本文关键字:不起作用 小提琴 嵌套 使用 SVG 元素      更新时间:2023-09-26

我需要在我的SVG图形中显示使用元素。

当我尝试从 g 元素中使用它们时,它不起作用。在一个小演示中,看起来 use 元素在 g 元素之外工作。

这里是小提琴(您可以向下滚动到 use 元素以查看演示):

http://jsfiddle.net/3dacnxdb/2/

为什么会这样?如何从 g 元素中显示它们?(我的图形由许多模块组成,我需要gs来分隔它们)

我感谢任何帮助!

<svg id="graphic">
  <defs>
    <clipPath id="icon-cp">
      <rect x="0" y="0" width="150" height="100" />
    </clipPath>
    <image id="icon-sprite" width="969" height="293"
    xlink:href="https://i.stack.imgur.com/TPx5h.png" />
    <g id="icon2" clip-path="url(#icon-cp)">
      <use xlink:href="#icon-sprite" transform="translate(-240,0)" />
    </g>
  </defs>
  <!--     ----------------------------------------
    Here is the question:
    
    the first use element is not displayed.
    The second one is displayed. (the elements are under this text)
    
    Why does it not work? 
    How can a use element be used within nested g elements?
    (to test it you can comment out the second use element, 
    even tough both use elements have the same attributes 
    no icon is visible anymore)
    ---------------------------------------- -->
  <!--  following does not work: -->
  <g id="testg">
    <use xlink:href="#icon2" x="100" y="50" />
  </g>
  <!--  following works: -->
  <use xlink:href="#icon2" x="100" y="50" />
  <!--  why???? -->

它确实有效。你的jsfiddle与你的内联代码不同(使用的x和y不一样)。

如果使<g>中的 x 和 y 值与外部相同,它将起作用。在非工作情况下,您将使用剪辑路径剪掉<use>的内容。

你看不到它,因为它们是叠加的... =)

<svg id="graphic">
  <defs>
    <clipPath id="icon-cp">
      <rect x="0" y="0" width="150" height="100" />
    </clipPath>
    <image id="icon-sprite" width="969" height="293" xlink:href="https://i.stack.imgur.com/TPx5h.png" />
    <g id="icon2" clip-path="url(#icon-cp)">
      <use xlink:href="#icon-sprite" transform="translate(-240,0)" />
    </g>
  </defs>
  <!--     ----------------------------------------
    Here is the question:
    
    the first use element is not displayed.
    The second one is displayed. (the elements are under this text)
    
    Why does it not work? How can a use element be used within nested g elements?
(to test it you can comment out the second use element, even tough both use elements have the same attributes no icon is visible anymore)
    ---------------------------------------- -->
  <!--  following does not work: -->
  <g id="testg">
    <use xlink:href="#icon2" x="0" y="0" />
  </g>
  <!--  following works: -->
  <use xlink:href="#icon2" x="100" y="50" />
  <!--  why???? -->