【问题标题】:why does <g> not work in <clipPath> in svg?为什么 <g> 在 svg 的 <clipPath> 中不起作用?
【发布时间】:2021-03-01 05:45:46
【问题描述】:

以下代码不起作用:

<svg>
    <defs>
        <clipPath id="test">
            <g>
                <rect x="0" y="0" width="10" height="10"></rect>
            </g>
        </clipPath>
    </defs>
    <rect x="0" y="0" width="100" height="100" clip-path="url(#test)"></rect>
</svg>

但这确实有效:

<svg>
    <defs>
        <clipPath id="test">
            <rect x="0" y="0" width="10" height="10"></rect>
        </clipPath>
    </defs>
    <rect x="0" y="0" width="100" height="100" clip-path="url(#test)"></rect>
</svg>

在我的项目中,组标签中有一些路径,我想将组重用为 clipPath 目标并同时显示路径。例如:

<svg>
    <defs>
        <g id="group">
            <path d="..."></path>
            <path d="..."></path>
            <path d="..."></path>
            <path d="..."></path>
        </g>
        <clipPath id="test">
            <use xlink:href="#group" fill="#000"></use>
        </clipPath>
    </defs>
    <!-- show the stroke of the group -->
    <use xlink:href="#group" stroke="#000"></use>
    <!-- at same time, clip the rect to make some animation as the background -->
    <rect x="0" y="0" width="100" height="100" clip-path="url(#test)"></rect>
</svg>

【问题讨论】:

  • 根据w3c,clipPath 允许的内容可以是任意数量的以下元素,按任意顺序:descriptive — desc、title、metadata animation — animate, animateColor, animateMotion, animateTransform, set shape — 圆形、椭圆、直线、路径、多边形、折线、矩形文本使用脚本

标签: svg


【解决方案1】:

因为 SVG 规范 says so

内容模型:
以下任意数量的元素,以任意顺序:

    描述性元素
动画元素
形状元素
“文字”
‘使用’

很遗憾,&lt;g&gt; 元素不在该列表中。

Firefox 很久以前就支持剪裁&lt;g&gt; 元素,直到我们注意到我们不是a)按照上述规范行事并且b)与其他实现兼容,因此我们限制我们的clipPath 实现保持一致。因此,如果您让 Chrome 和 Safari 参与规范更改,我们可能会同意。

请注意,您可以通过剪切指向 &lt;g&gt; 元素的 &lt;use&gt; 元素来解决此问题。

【讨论】:

  • 谢谢。经过几次尝试,我设法将所有 合并到一个 中,现在看起来可以正常工作了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-05
  • 2015-01-17
相关资源
最近更新 更多