使用CSS方法如何设置图像来填充SVG中的路径? [英] Using CSS approach how to set an image to fill a path in SVG?
问题描述
我想创建一个CSS类来填充一个路径的图像,可以应用在任何SVG路径和填充图像的路径。图片必须拉伸以适合该路径。
I want to create a CSS class to fill a path with image that can be applied on any SVG path and fill that path with image. The image must be stretch to fit that path.
要实现这一点;我使用图片标签创建了一个模式,并将宽度和高度设置为 100%。但图片需要容器的整个屏幕的100%而不是 objectBoundingBox (在这种情况下 svg 标记)。
To achieve this; I create a pattern with image tag and set the width and height as 100%. but the image takes 100% of the whole screen instead of objectBoundingBox of the container (in this case svg tag).
下面是示例代码:
.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>
可能是我做错了。
请为此问题提出任何解决方案。
Please suggest any solution for this problem.
推荐答案
这是您的工作 - http://jsfiddle.net/eAfTc/
Here's your thing working - 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 和 patternUnit ,他们会不同的东西。
Note that there's a patternContentUnits and a patternUnits, they do different things. Personally I prefer to use a viewBox for defining the coordinate system.
这里是一个新例子
Here's a new example showing the pattern applied to various elements of different sizes and aspect ratios, it also gets rid of the first svg fragment.
更新:我向< pattern>元素添加了'preserveAspectRatio',以及一个显示伸展和缩放的新示例。
Update: I added 'preserveAspectRatio' to the <pattern> element, and a new example showing the stretching and scaling.
这篇关于使用CSS方法如何设置图像来填充SVG中的路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!