randomColor.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. var defaults = require('./defaults');
  2. var random = require('./random');
  3. var Color = require('./Color');
  4. var seedRandom = require('./seedRandom');
  5. var isFn = require('./isFn');
  6. exports = function() {
  7. var options =
  8. arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
  9. defaults(options, defOpts);
  10. var count = options.count;
  11. var randomH = options.randomH,
  12. randomL = options.randomL,
  13. randomS = options.randomS;
  14. if (!isFn(randomH)) {
  15. var seed = options.seed || random(0, 100000);
  16. randomH = seedRandom(seed, 0, 360, false);
  17. randomL = seedRandom(seed + 1, 0, 1);
  18. randomS = seedRandom(seed + 2, 0, 1);
  19. }
  20. if (count > 1) {
  21. var colors = [];
  22. for (var i = 0; i < count; i++) {
  23. colors.push(
  24. exports(
  25. defaults(
  26. {
  27. count: 1,
  28. randomH: randomH,
  29. randomL: randomL,
  30. randomS: randomS
  31. },
  32. options
  33. )
  34. )
  35. );
  36. }
  37. return colors;
  38. }
  39. var hue = options.hue || randomH();
  40. var lightness = options.lightness || randomL().toFixed(2);
  41. var saturation = options.saturation || randomS().toFixed(2);
  42. var color = new Color({
  43. val: [hue, Math.round(saturation * 100), Math.round(lightness * 100)],
  44. model: 'hsl'
  45. });
  46. switch (options.format) {
  47. case 'hsl':
  48. return color.toHsl();
  49. case 'rgb':
  50. return color.toRgb();
  51. default:
  52. return color.toHex();
  53. }
  54. };
  55. var defOpts = {
  56. count: 1,
  57. format: 'hex'
  58. };
  59. module.exports = exports;