Thursday, 18 February 2016

JavaScript lighten RGB by a percentage

// colour: numeric rgb representation
// percent: -100..100
function lightenRGB(color, percent) {
  var
 t = percent < 0 ? 0 : 255,
 p = Math.min(100, Math.abs(percent) / 100);

  function lightenComponent(bitShift) {
    var c = color >> bitShift & 0xff;
    return (Math.round((t - c) * p) + c) << bitShift;
  }

  return lightenComponent(16) + lightenComponent(8) + lightenComponent(0);
}