index.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. import quantize from "quantize";
  2. const toString = array =>
  3. `#${((1 << 24) + (array[0] << 16) + (array[1] << 8) + array[2])
  4. .toString(16)
  5. .slice(1)}`;
  6. const proxy = (data, fn) => {
  7. if (data.map(item => Array.isArray(item)).includes(true)) {
  8. return data.map(item => fn(item));
  9. } else {
  10. return fn(data);
  11. }
  12. };
  13. const getGray = rgb => (rgb[0] * 299 + rgb[1] * 587 + rgb[2] * 114) / 1000;
  14. const colorThief = pixels => ({
  15. palette(count, quality) {
  16. if (typeof count === "undefined" || count < 2 || count > 256) {
  17. count = 10;
  18. }
  19. if (typeof quality === "undefined" || quality < 1) {
  20. quality = 10;
  21. }
  22. // Store the RGB values in an array format suitable for quantize function
  23. let pixelArray = [];
  24. for (
  25. let i = 0, offset, r, g, b, a;
  26. i < pixels.length / 4;
  27. i = i + quality
  28. ) {
  29. offset = i * 4;
  30. r = pixels[offset + 0];
  31. g = pixels[offset + 1];
  32. b = pixels[offset + 2];
  33. a = pixels[offset + 3];
  34. // If pixel is mostly opaque and not white
  35. if (a >= 125) {
  36. if (!(r > 250 && g > 250 && b > 250)) {
  37. pixelArray.push([r, g, b]);
  38. }
  39. }
  40. }
  41. this._data = quantize(pixelArray, count).palette() || null;
  42. return this;
  43. },
  44. color(quality) {
  45. let palette = this.palette(5, quality)._data;
  46. if (palette) {
  47. this._data = palette[0];
  48. return this;
  49. } else {
  50. console.error(
  51. "[MiniApp Color Thief] getColor has error: palette length is zero."
  52. );
  53. }
  54. },
  55. __proto__: {
  56. get() {
  57. return this._data;
  58. },
  59. getHex() {
  60. return proxy(this._data, toString);
  61. },
  62. getGray() {
  63. return proxy(this._data, getGray);
  64. },
  65. isDark() {
  66. return proxy(this._data, data => getGray(data) < 127.5);
  67. },
  68. isLight() {
  69. return proxy(this._data, data => getGray(data) >= 127.5);
  70. }
  71. }
  72. });
  73. export default colorThief;