gpt4 book ai didi

css - 使用 CSS 方法如何设置图像以填充 SVG 中的路径?

转载 作者:技术小花猫 更新时间:2023-10-29 11:18:24 24 4
gpt4 key购买 nike

我想创建一个 CSS 类来用可应用于任何 SVG 路径的图像填充路径,并用图像填充该路径。图片必须拉伸(stretch)以适合该路径。

为了达到这个目的;我使用 image 标签创建了一个图案,并将宽度和高度设置为 100%。但图像占据了 100% 的整个屏幕,而不是容器的objectBoundingBox(在本例中为svg 标签)。

示例代码如下:

.myClass {
fill: url(#image);
stroke: red;
stroke-width: 5;
}

<svg id='pattern' xmlns="http://www.w3.org/2000/svg" version="1.1">
<defs>
<pattern id='image' x=0 y=0 width="100%" height="100%" patternUnits='objectBoundingBox'>
<image xlink:href='myImage.png' x=0 y=0 width="100%" height="100%" preserveAspectRatio="none"></image>
</pattern>
</defs>
</svg>
<svg id='triangle' xmlns="http://www.w3.org/2000/svg" version="1.1" width='300px' height='300px'>
<path d='M0 0 L300 0 L300 300 Z' class='myClass'></path>
</svg>

可能是我做错了什么。

请为这个问题提出任何解决方案。

最佳答案

这是你的工作 - http://jsfiddle.net/eAfTc/

.myClass {
fill: url(#image);
stroke: red;
stroke-width: 5;
}

<svg id='pattern' xmlns="http://www.w3.org/2000/svg" version="1.1">
<defs>
<pattern id='image' width="1" height="1" viewBox="0 0 100 100" preserveAspectRatio="none">
<image xlink:href='http://dummyimage.com/600x400/abc/333' width="100" height="100" preserveAspectRatio="none"></image>
</pattern>
</defs>
</svg>
<svg id='triangle' xmlns="http://www.w3.org/2000/svg" version="1.1" width='300px' height='300px'>
<path d='M0 0 L300 0 L300 300 Z' class='myClass'></path>
</svg>

请注意,有一个 patternContentUnits和一个 patternUnits ,他们做不同的事情。我个人更喜欢使用 viewBox 来定义坐标系。

这是一个 new example显示应用于不同大小和纵横比的各种元素的图案,它还摆脱了第一个 svg 片段。

更新:我向 元素添加了“preserveAspectRatio”,并添加了一个显示拉伸(stretch)和缩放的新示例。

关于css - 使用 CSS 方法如何设置图像以填充 SVG 中的路径?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13914868/

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