nearest.js 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. const getSprite = pokemon => `https://img.pokemondb.net/sprites/sword-shield/icon/${pokemon}.png`
  2. const onColorChange = () => {
  3. const numPoke = document.getElementById("num-poke")?.value;
  4. document.getElementById("num-poke-display").innerHTML = numPoke;
  5. const closeCoeff = document.getElementById("close-coeff")?.value;
  6. document.getElementById("close-coeff-display").innerHTML = closeCoeff;
  7. const bestList = document.getElementById("best-list");
  8. bestList.innerHTML = ''; // do the lazy thing
  9. const color = document.getElementById("color-input")?.value;
  10. if (color.length !== 6) {
  11. return;
  12. }
  13. document.querySelector("body").setAttribute("style", `background: #${color}`);
  14. const colorValues = [
  15. Number.parseInt(color.substring(0, 2), 16),
  16. Number.parseInt(color.substring(2, 4), 16),
  17. Number.parseInt(color.substring(4, 6), 16),
  18. ];
  19. database.map(([name, x, ...y]) => ({
  20. name,
  21. score: x - closeCoeff * y.map((yc, i) => yc * colorValues[i]).reduce((x, y) => x + y),
  22. avgColor: y,
  23. }))
  24. .sort((a, b) => a.score - b.score)
  25. .slice(0, numPoke)
  26. .forEach(({ name, avgColor}) => {
  27. const li = document.createElement("li");
  28. const img = document.createElement("img");
  29. const tile = document.createElement("div");
  30. const hexColor = avgColor.map(c => Math.round(c).toString(16).padStart(2, "0")).reduce((x, y) => x + y);
  31. tile.setAttribute("style", `width: 25px; height: 25px; background-color: #${hexColor}`)
  32. img.setAttribute("src", getSprite(name));
  33. li.appendChild(img)
  34. li.appendChild(document.createTextNode(name));
  35. li.appendChild(tile)
  36. li.setAttribute("style", "display: flex; flex-flow: row nowrap; justify-content: space-between; min-width: 100px")
  37. bestList.appendChild(li);
  38. });
  39. };
  40. const onRandomColor = () => {
  41. const colorInput = document.getElementById("color-input");
  42. colorInput.value = hsvToRGB(Math.random(), 0.9, 0.9);
  43. onColorChange();
  44. };
  45. // mostly stolen from https://stackoverflow.com/a/17243070
  46. // adapted slightly
  47. const hsvToRGB = (h, s, v) => {
  48. var r, g, b, i, f, p, q, t;
  49. i = Math.floor(h * 6);
  50. f = h * 6 - i;
  51. p = v * (1 - s);
  52. q = v * (1 - f * s);
  53. t = v * (1 - (1 - f) * s);
  54. switch (i % 6) {
  55. case 0: r = v, g = t, b = p; break;
  56. case 1: r = q, g = v, b = p; break;
  57. case 2: r = p, g = v, b = t; break;
  58. case 3: r = p, g = q, b = v; break;
  59. case 4: r = t, g = p, b = v; break;
  60. case 5: r = v, g = p, b = q; break;
  61. }
  62. return [r, g, b].map(c => Math.round(c * 255).toString(16).padStart(2, "0")).reduce((x, y) => x + y);
  63. }