将SVG蒙版应用于形状填充

时间:2015-08-03 20:34:31

标签: javascript css svg

我想根据下面定义的渐变使对象的填充变暗。但是,当面具越过填充物时,它会变亮。我假设这必须基于如何混合颜色的决定。它使用加色而不是减色。我需要在面罩上方涂抹过滤器吗?我觉得渐变或蒙版定义中应该有一个属性,以使其按照我想要的方式混合颜色。下面的代码和小提琴链接:

<svg width="400px" height="500px">
  <defs>
    <linearGradient id="mygradient" gradientUnits="userSpaceOnUse"
                    x1="0" y1="0" x2="0" y2="100%">
      <stop offset="0" stop-color="black"/>
      <stop offset="0.5" stop-color="white"/>                
      <stop offset="1" stop-color="black"/>
    </linearGradient>

      <mask id="mask1" x="0" y="0" width="400" height="500" MaskUnits="userSpaceOnUse" color-interpolation="sRGB">
    <rect x="0" y="0" width="400" height="500"
        style="stroke:none; fill: url(#mygradient)"/>
  </mask>
  </defs>



  <g fill="red" mask= "url(#mask1)" stroke="black" stroke-width="4"
    feblend="Multiply">

    <rect x="5" y="5" width="390" height="90"/>
    <rect x="5" y="105" width="390" height="90"/>
    <rect x="5" y="205" width="390" height="90"/>
    <rect x="5" y="305" width="390" height="90"/>
     <rect x="5" y="405" width="390" height="90"/>

  </g>

</svg>

https://jsfiddle.net/6q3x8x5u/

2 个答案:

答案 0 :(得分:0)

您可以使用简单的<rect>替换蒙版,并使用正确的混合模式。

<g>下方):

<rect x="0" y="0" width="400" height="500" style="stroke:none;
  fill: url(#mygradient); mix-blend-mode: multiply" />

请参阅此fiddle

答案 1 :(得分:0)

为什么戴面具?面具用于改变透明度,而不是颜色。

您的SVG中有一个您没有使用的渐变。如果你调整渐变的颜色,你可以得到你想要的声音。

<svg width="400px" height="500px">
  <defs>
    <linearGradient id="mygradient" gradientUnits="userSpaceOnUse"
                    x1="0" y1="0" x2="0" y2="100%">
      <stop offset="0" stop-color="black"/>
      <stop offset="0.5" stop-color="red"/>                
      <stop offset="1" stop-color="black"/>
    </linearGradient>
  </defs>
  
  
  
  <g fill="url(#mygradient)" stroke="black" stroke-width="4"
    feblend="Multiply">

    <rect x="5" y="5" width="390" height="90"/>
    <rect x="5" y="105" width="390" height="90"/>
    <rect x="5" y="205" width="390" height="90"/>
    <rect x="5" y="305" width="390" height="90"/>
     <rect x="5" y="405" width="390" height="90"/>

  </g>

</svg>