Advertisement
Guest User

Untitled

a guest
Apr 26th, 2017
53
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.11 KB | None | 0 0
  1. function blendColors() {
  2. var args = [].prototype.slice.call(arguments);
  3. var base = [0, 0, 0, 0];
  4. var mix;
  5. var added;
  6. while (added = args.shift()) {
  7. if (typeof added[3] === 'undefined') {
  8. added[3] = 1;
  9. }
  10. // check if both alpha channels exist.
  11. if (base[3] && added[3]) {
  12. mix = [0, 0, 0, 0];
  13. // alpha
  14. mix[3] = 1 - (1 - added[3]) * (1 - base[3]);
  15. // red
  16. mix[0] = Math.round((added[0] * added[3] / mix[3]) + (base[0] * base[3] * (1 - added[3]) / mix[3]));
  17. // green
  18. mix[1] = Math.round((added[1] * added[3] / mix[3]) + (base[1] * base[3] * (1 - added[3]) / mix[3]));
  19. // blue
  20. mix[2] = Math.round((added[2] * added[3] / mix[3]) + (base[2] * base[3] * (1 - added[3]) / mix[3]));
  21.  
  22. } else if (added) {
  23. mix = added;
  24. } else {
  25. mix = base;
  26. }
  27. base = mix;
  28. }
  29.  
  30. return mix;
  31. }
  32.  
  33. // outputs [85, 170, 0, 0.75]
  34. console.log(blendColors(
  35. [0, 0, 0, 0],
  36. [255, 255, 255, 0],
  37. [255, 0, 0, .5],
  38. [0, 255, 0, .5]
  39. ));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement