gpt4 book ai didi

html - 使用 SVG 和渐变作为填充

转载 作者:太空狗 更新时间:2023-10-29 15:18:23 24 4
gpt4 key购买 nike

我一直在尝试将我的 SVG 图标外部化到一个文件中,并使用像 <svg><use xlink:href="file.svg#icon" /></svg> 这样的标记来引用它们.从理论上讲,这确实很好用,但是不同的浏览器在渲染方面存在问题。当使用 <use> 引用符号时,所有浏览器都能够正确呈现 svg。在文件中直接打开 svg 文件的 url。

简而言之,有没有跨浏览器的方式来获取SVG linearGradient当用 <svg><use/></svg> 引用符号时,s 用作元素的填充物在标记中?

我设置了一个 plunker 来演示这个问题: http://plnkr.co/edit/feKvZ7?p=preview

简化后,标记如下:

<!DOCTYPE html>
<html>
<body>
<h1>SVG sprite test</h1>
<svg width="100" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<use xlink:href="icon.svg#icon" />
</svg>
</body>
</html>

SVG 文件如下所示:

  <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<defs>
<linearGradient id="gradient">
<stop offset="0" stop-color="black" />
<stop offset="1" stop-color="white" />
</linearGradient>
</defs>
<symbol id="icon" viewBox="0 0 100 100">
<circle cx="50" cy="50" r="40" stroke="black" fill="url(#gradient)" />
</symbol>

<use id="iconuse" xlink:href="#icon" width="100" height="100" />

</svg>

这是它在不同浏览器中的样子: Different results of rendering linear gradients for symbols in different browser

最佳答案

symbol标签用于隐藏其中的元素。 symbol 内的元素使用 <use> 调用通过其独特的指示器进行命令。
因此,最好使用这种调用单个元素的方法,而不是调用整个symbol

此外,使用元素时<use>落入shadow DOM在某些情况下使用 CSS 变得不可能
因此,最好删除symbol内部的所有样式,直接赋值给use。命令

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<defs>
<linearGradient id="gradient">
<stop offset="0" stop-color="black" />
<stop offset="1" stop-color="white" />
</linearGradient>
</defs>
<symbol id="icon" viewBox="0 0 100 100">
<circle id="circle" cx="50" cy="50" r="40" />
<rect id="rect" x="100" y="10" width="100" height="100" />
</symbol>

<use class="iconuse" xlink:href="#circle" width="100" height="100" fill="url(#gradient)" stroke="black" />
<use class="iconuse" xlink:href="#rect" width="100" height="100" fill="url(#gradient)" />
</svg>

关于html - 使用 SVG 和渐变作为填充,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44235845/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com