transparentify.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. var utils = require('../utils')
  2. , nodes = require('../nodes');
  3. /**
  4. * Returns the transparent version of the given `top` color,
  5. * as if it was blend over the given `bottom` color.
  6. *
  7. * Examples:
  8. *
  9. * transparentify(#808080)
  10. * => rgba(0,0,0,0.5)
  11. *
  12. * transparentify(#414141, #000)
  13. * => rgba(255,255,255,0.25)
  14. *
  15. * transparentify(#91974C, #F34949, 0.5)
  16. * => rgba(47,229,79,0.5)
  17. *
  18. * @param {RGBA|HSLA} top
  19. * @param {RGBA|HSLA} [bottom=#fff]
  20. * @param {Unit} [alpha]
  21. * @return {RGBA}
  22. * @api public
  23. */
  24. function transparentify(top, bottom, alpha){
  25. utils.assertColor(top);
  26. top = top.rgba;
  27. // Handle default arguments
  28. bottom = bottom || new nodes.RGBA(255, 255, 255, 1);
  29. if (!alpha && bottom && !bottom.rgba) {
  30. alpha = bottom;
  31. bottom = new nodes.RGBA(255, 255, 255, 1);
  32. }
  33. utils.assertColor(bottom);
  34. bottom = bottom.rgba;
  35. var bestAlpha = ['r', 'g', 'b'].map(function(channel){
  36. return (top[channel] - bottom[channel]) / ((0 < (top[channel] - bottom[channel]) ? 255 : 0) - bottom[channel]);
  37. }).sort(function(a, b){return b - a;})[0];
  38. if (alpha) {
  39. utils.assertType(alpha, 'unit', 'alpha');
  40. if ('%' == alpha.type) {
  41. bestAlpha = alpha.val / 100;
  42. } else if (!alpha.type) {
  43. bestAlpha = alpha = alpha.val;
  44. }
  45. }
  46. bestAlpha = Math.max(Math.min(bestAlpha, 1), 0);
  47. // Calculate the resulting color
  48. function processChannel(channel) {
  49. if (0 == bestAlpha) {
  50. return bottom[channel]
  51. } else {
  52. return bottom[channel] + (top[channel] - bottom[channel]) / bestAlpha
  53. }
  54. }
  55. return new nodes.RGBA(
  56. processChannel('r'),
  57. processChannel('g'),
  58. processChannel('b'),
  59. Math.round(bestAlpha * 100) / 100
  60. );
  61. }
  62. transparentify.params = ['top', 'bottom', 'alpha'];
  63. module.exports = transparentify;