如何在使用时更改 SVG 图案的颜色?

Dan*_*iel 5 svg colors svg-filters

我想在使用时更改图案的颜色。

例如,我想在红色描边圆圈中有一个绿色图案。

<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>
Run Code Online (Sandbox Code Playgroud)

http://codepen.io/anon/pen/RVNmRY

是否可以在不必为每种颜色创建新图案的情况下这样做?

我在评论中读到,这可能可以使用过滤器(/sf/answers/1499912151/)。但我不知道怎么做。

War*_*ama 6

如果您用所需的颜色填充圆圈,然后将图案用作蒙版,它就会起作用。以下是绿色和洋红色的示例:

<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>
Run Code Online (Sandbox Code Playgroud)


Mic*_*any 5

以下是如何使用“蓝屏”技术通过滤镜对形状重新着色。该滤镜仅保留红色分量(矩阵中的第一个 1),将蓝色转换为绿色(下一个“1”),并保持不透明度不变(最后一个“1”)。这个特定的过滤器显然只适用于您的示例,但您可以编写一个更通用的过滤器来使用特定的源颜色作为将转换为其他颜色的颜色。

<svg width="300" height="300" viewBox="0 0 300 300"
    xmlns="http://www.w3.org/2000/svg">
  <defs>
  <filter id="blue-to-green">
     <feColorMatrix type="matrix" values="1 0 0 0 0
                                          0 0 1 0 0 
                                          0 0 0 0 0 
                                          0 0 0 1 0"/>
  </filter>
  
    <pattern id="checked" width="2" height="2" stroke="blue" 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)" filter="url(#blue-to-green)"/>
  <circle cx="120" cy="60" r="50" stroke="blue" fill="url(#checked)"/>
</svg>
Run Code Online (Sandbox Code Playgroud)

  • 谢谢。是的,就目前情况而言,必须为每种颜色添加一个过滤器。与必须为每种颜色添加图案相比,这并没有太大的改进。 (2认同)