简单使用'defs'不显示任何内容



我是SVG的总菜鸟。通过了基本语法,我正在用defs语法挣扎。

使用Chrome测试简化的用例:

这很好:

<svg viewBox="0 0 400 100" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
  <g><path id="red" fill="red"  d="M10 10 H 90 V 90 H 10 Z" stroke="black"/></g>
  <g transform="translate(200, 0)"><path id="blue" fill="blue" d="M10 10 H 60 V 60 H 10 Z" stroke="black"/></g>
</svg>

但这没有显示任何内容:

<svg viewBox="0 0 400 100" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
  <defs>
        <path id="red" fill="red" />
        <path id="blue" fill="blue" />
  </defs>
  <g><use xlink:href="#red" d="M10 10 H 90 V 90 H 10 Z" stroke="black"/></g>
  <g transform="translate(200, 0)"><use xlink:href="blue" d="M10 10 H 60 V 60 H 10 Z" stroke="black"/></g>
</svg>

假设这是一个简单的监督...另外,symbols可以更好地解决。我只是读过两者,但这并不明显是什么比另一个更好。

update

根据罗伯特的评论,我修复了丢失的#。是否有一种方法可以使此代码与g roup一起使用,而不是像下面的代码中的DEF内部使用path

<svg viewBox="0 0 400 100" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
  <defs>
        <g id="red" fill="red" />
        <g id="blue" fill="blue" />
  </defs>
  <use xlink:href="#red"><path  d="M10 10 H 90 V 90 H 10 Z" stroke="black"/></use>
  <use xlink:href="#blue" ><path d="M10 10 H 60 V 60 H 10 Z" stroke="black"/></use>
 </svg>

使用元素不使用D属性,因此它们仍然需要进入路径元素。

您的第二个使用元素也缺少xlink中的#字符:href属性。

<svg viewBox="0 0 400 100" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
  <defs>
        <path id="red" fill="red" d="M10 10 H 90 V 90 H 10 Z" />
        <path id="blue" fill="blue" d="M10 10 H 60 V 60 H 10 Z" />
  </defs>
  <g><use xlink:href="#red" stroke="black"/></g>
  <g transform="translate(200, 0)"><use xlink:href="#blue" stroke="black"/></g>
 </svg>

或仅使用CSS的样式标签。您可能需要扩展基本解析器以应对一些简单的CSS。

<svg viewBox="0 0 400 100" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
  <defs>
        <style>
          .red {
            fill: red;
          }
          .blue {
            fill : blue;
          }
        </style>
  </defs>
  <path class="red" d="M10 10 H 90 V 90 H 10 Z" stroke="black"/>
  <path class="blue" d="M10 10 H 60 V 60 H 10 Z" stroke="black"/>
 </svg>

最新更新