如何在使用时更改SVG图案的颜色? [英] How to change color of SVG pattern on usage?
问题描述
我想在使用时更改图案的颜色.
I would like to change the color of pattern upon usage.
例如,我想在红色的描边圆圈中添加绿色图案.
For example, I would like to have a green pattern in the red stroked circle.
<svg width="300" height="300" viewBox="0 0 300 300"
xmlns="http://www.w3.org/2000/svg">
<defs>
<pattern id="checked" width="2" height="2" stroke="black" stroke-linecap="square" stroke-width="1" patternTransform="rotate(45) scale(2)"
patternUnits="userSpaceOnUse">
<line x1="0" y1="0" x2="0" y2="2"></line>
<line x1="0" y1="0" x2="2" y2="0"></line>
</pattern>
</defs>
<circle cx="60" cy="60" r="50" stroke="red" fill="url(#checked)"/>
<circle cx="120" cy="60" r="50" stroke="blue" fill="url(#checked)"/>
</svg>
http://codepen.io/anon/pen/RVNmRY
是否可以这样做,而不必为每种颜色创建新的图案?
Is it possible to do so without having to create a new pattern for every color?
我已在评论中看到,使用过滤器可以实现此目的( https://stackoverflow.com/a/21427316/1981832 ).但是我不知道怎么办.
I have read in a comment that this might be possible using filters (https://stackoverflow.com/a/21427316/1981832). But I don't know how.
推荐答案
如果您用所需的颜色填充圆圈,然后将图案用作遮罩,则该方法将起作用.这是绿色和洋红色的示例:
It works if you fill the circles with the desired color and then apply the pattern as a mask. Here is an example for green and magenta:
<svg width="300" height="300" viewBox="0 0 300 300"
xmlns="http://www.w3.org/2000/svg">
<defs>
<pattern id="checked" width="2" height="2" stroke="white" stroke-linecap="square" stroke-width="1" patternTransform="rotate(45) scale(2)"
patternUnits="userSpaceOnUse">
<line x1="0" y1="0" x2="0" y2="2"></line>
<line x1="0" y1="0" x2="2" y2="0"></line>
</pattern>
<mask id="checked-mask" x="0" y="0" width="1" height="1" >
<rect x="0" y="0" width="1000" height="1000" fill="url(#checked)" />
</mask>
</defs>
<circle cx="60" cy="60" r="50" stroke="red" mask="url(#checked-mask)" fill="green" />
<circle cx="120" cy="60" r="50" stroke="blue" mask="url(#checked-mask)" fill="magenta" />
</svg>
这篇关于如何在使用时更改SVG图案的颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!