javascriptmathcolorsblendingcolor-blending

Soft Light Blending Mode


I am trying to write a function that calculates the soft light given a foreground and a background color. The function is below;

var background = '0xFFFFFF';
var foreground = '0x47768C';

var calculateSoftlight = function (background, foreground) {
  var intBackground = parseInt(background, 16);
  var intForeground = parseInt(foreground, 16);

  var softlight = (1 - (2 * intForeground)) * (intBackground*intBackground) + (2 * intForeground * intBackground);
  return softlight.toString(16);
}

calculateSoftlight(background, foreground); //-8eed155338bb200000 

I am using the Pegtop formula as listed here; http://en.wikipedia.org/wiki/Blend_modes. I am unsure of the correct implementation of this. Any ideas?


Solution

  • Apply the formula to each RGB value instead of using Hex. If you need to use Hex as an input you'll probably need to convert.

    You will need to normalize each value (so value / 255) and use that in the formula. Then multiply (and round) the result by 255 to convert back to 8-bit value.

    Something like this should be close, I haven't used that formula specifically though so this is untested.

    var top = top / 255,
        bot = bot / 255;
    
    top = ((1 - 2*bot)*Math.pow(top, 2)) + 2*bot*top,
    top = Math.round(top * 255);