【问题标题】:How do I control the color of an SVG drop-shadow?如何控制 SVG 投影的颜色?
【发布时间】:2016-10-28 08:36:07
【问题描述】:

我有以下 SVG:

<defs>
    <filter id="dropshadow">
        <feOffset result="offOut" in="SourceAlpha" dx="2" dy="2"></feOffset>
        <feGaussianBlur result="blurOut" in="offOut" stdDeviation="2"></feGaussianBlur>
        <feBlend in="SourceGraphic" in2="blurOut" mode="normal"></feBlend>
    </filter>
</defs>

但是,我该如何修改它以添加控制阴影颜色的功能?

【问题讨论】:

    标签: svg svg-filters


    【解决方案1】:

    您应该使用 feColorMatrix 中的固定偏移列来指定准确的颜色。具体来说,例如,如果您想要 RGB(128,128,0),则将其转换为单位比例 (0.5, 0.5,0) 并将其放入颜色矩阵的第五列。在 sRGB 颜色空间中指定这一点也很重要。

    <defs>
        <filter id="dropshadow" color-interpolation-filters="sRGB">
            <feOffset result="offOut" in="SourceAlpha" dx="2" dy="2"/>
            <feColorMatrix in="offOut" result ="matrixOut" type="matrix"                           
                                         values="0 0 0 0 0.5
                                                 0 0 0 0 0.5
                                                 0 0 0 0 0 
                                                 0 0 0 1 0" />
            <feGaussianBlur result="blurOut" in="matrixOut" stdDeviation="2"/>
            <feBlend in="SourceGraphic" in2="blurOut" mode="normal"/>
        </filter>
    </defs>
    

    【讨论】:

      【解决方案2】:

      您可以使用 feColorMatrix 元素。尝试使用 values 属性中的数字。

      <svg width="100%" height="300px">
      <defs>
          <filter id="dropshadow" width="130%" height="130%">
              <feOffset result="offOut" in="SourceGraphic" dx="5" dy="5"></feOffset>
              <feColorMatrix result="matrixOut" in="offOut" type="matrix"
            values="0.2 0 0 0 0 0 0.2 0 0 1 0 0 0.2 0 0 0 0 0 1 0" />
              <feGaussianBlur result="blurOut" in="matrixOut" stdDeviation="2"></feGaussianBlur>
              <feBlend in="SourceGraphic" in2="blurOut" mode="normal"></feBlend>
          </filter>
      </defs>
        <rect x="20" y="20" width="50" height="50" fill="red" filter="url(#dropshadow)"></rect>
      </svg>

      【讨论】:

      • 无法让它在 Chrome MSIE(11) 或 FF 中工作。 .我的 SVG 代码中有这个:
      • 答案中的代码 sn-p 当然适用于 FF,因为这是我用来创建和测试它的。在 Chrome 中似乎也可以,那里也有石灰绿色的阴影。请注意,还有其他更改,例如你的 feOffset 中的 SourceAlpha 是我的 SourceGraphic。
      • 取决于您在 feColorMatrix 中使用的值
      • 有趣。我使用 JavaScript 创建 SVG 元素,但现在我尝试在独立的 HTML 文件中使用它,它可以工作。不过,制作矩阵需要一些思考。
      猜你喜欢
      • 1970-01-01
      • 2011-12-19
      • 1970-01-01
      • 1970-01-01
      • 2015-08-09
      • 2018-08-03
      • 2018-06-23
      • 2021-12-21
      相关资源
      最近更新 更多