svgsvg-filters

How to add two feColorMatrix results? Just the sum of each RGB channel


I can't seem to find this anywhere, but is there a way in an SVG filter to simply add two colors from 2 feColorMatrix's together? While there are many Porter-Duff operations available, the simple plus one doesn't seem to exist.

My color matrix's are built dynamically, so the values I send in to both will be different, but as a static example. Basically, I have a shape with a fill of rgb(68,114,196). I have two color matrix's that use that to get a new color. The result of the first one is RGB(43, 71,123) and the second one is RGB(8,13,22). Now I just want to add these together to get RGB(52, 88, 156). Simple, right? I can find anyway in feBlend, feComposite or other ways to do this.

    <svg x="50" y="20" width="144" height="144" overflow="visible">
              <defs>
          <filter id="newColorFilter" color-interpolation-filters="sRGB">
        
        <feColorMatrix in="SourceGraphic" result="color1" type="matrix" values="0.626095953 0 0 0 0 0 0.626095953 0 0 0 0 0 0.626095953 0 0 0 0 0 1 0"></feColorMatrix>
        <feColorMatrix in="SourceGraphic" result="color2" type="matrix" values="0.111116039 0 0 0 0 0 0.111116039 0 0 0 0 0 0 0.111116039 0 0 0 0 0 1 0"></feColorMatrix>
    
        <!--need something here to add the two colors together, like this (but this doesn't work
    <feComposite operator="plus" in="color1" in2="color2"></feComposite>-->
    </filter>
    </defs>
            <path d="M0,0 144,0 144,144 0,144 Z " fill="rgb(68,114,196)" filter="url(#newColorFilter)"></path>
 </svg>

Does anyone know a simple way to sum two colors in a filter?


Solution

  • <feComposite> has an arithmetic mode where you can define the composition formula by hand. If i1 and i2 are the input channels, you can set four parameters:

    result = k1*i1*i2 + k2*i1 + k3*i2 + k4
    

    A simple addition can be achieved with k2 = k3 = 1. (All other parameters are 0 by default.)

    Yout second color matrix had an error (one value too much), btw.

    <svg x="50" y="20" width="144" height="144" overflow="visible">
        <defs>
        <filter id="newColorFilter" color-interpolation-filters="sRGB">
            
            <feColorMatrix in="SourceGraphic" result="color1" type="matrix" values="0.626095953 0 0 0 0 0 0.626095953 0 0 0 0 0 0.626095953 0 0 0 0 0 1 0"></feColorMatrix>
            <feColorMatrix in="SourceGraphic" result="color2" type="matrix" values="0.111116039 0 0 0 0 0 0.111116039 0 0 0 0 0 0.111116039 0 0 0 0 0 1 0"></feColorMatrix>
    
            <feComposite operator="arithmetic" k2="1" k3="1" in="color1" in2="color2"></feComposite>
        </filter>
        </defs>
        <path d="M0,0 144,0 144,144 0,144 Z " fill="rgb(68,114,196)" filter="url(#newColorFilter)"></path>
     </svg>