You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

letteravatar.js 1.9 kB

2 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. function LetterAvatar(name, size, color) {
  2. name = name || "";
  3. size = size || 60;
  4. var colours = [
  5. "#1abc9c",
  6. "#2ecc71",
  7. "#3498db",
  8. "#9b59b6",
  9. "#34495e",
  10. "#16a085",
  11. "#27ae60",
  12. "#2980b9",
  13. "#8e44ad",
  14. "#2c3e50",
  15. "#f1c40f",
  16. "#e67e22",
  17. "#e74c3c",
  18. "#00bcd4",
  19. "#95a5a6",
  20. "#f39c12",
  21. "#d35400",
  22. "#c0392b",
  23. "#bdc3c7",
  24. "#7f8c8d",
  25. ],
  26. nameSplit = String(name).split(" "),
  27. initials,
  28. charIndex,
  29. colourIndex,
  30. canvas,
  31. context,
  32. dataURI;
  33. if (nameSplit.length == 1) {
  34. initials = nameSplit[0] ? nameSplit[0].charAt(0) : "?";
  35. } else {
  36. initials = nameSplit[0].charAt(0) + nameSplit[1].charAt(0);
  37. }
  38. let initials1 = initials.toUpperCase();
  39. if (window.devicePixelRatio) {
  40. size = size * window.devicePixelRatio;
  41. }
  42. charIndex = (initials == "?" ? 72 : initials.charCodeAt(0)) - 64;
  43. colourIndex = charIndex % 20;
  44. canvas = document.createElement("canvas");
  45. canvas.width = size;
  46. canvas.height = size;
  47. context = canvas.getContext("2d");
  48. context.fillStyle = color ? color : colours[colourIndex - 1];
  49. context.fillRect(0, 0, canvas.width, canvas.height);
  50. context.font = Math.round(canvas.width / 2) + "px 'Microsoft Yahei'";
  51. context.textAlign = "center";
  52. context.fillStyle = "#FFF";
  53. context.fillText(initials1, size / 2, size / 1.5);
  54. dataURI = canvas.toDataURL();
  55. canvas = null;
  56. return dataURI;
  57. }
  58. LetterAvatar.transform = function () {
  59. Array.prototype.forEach.call(
  60. document.querySelectorAll("img[avatar]"),
  61. function (img, name, color) {
  62. name = img.getAttribute("avatar");
  63. color = img.getAttribute("color");
  64. img.src = LetterAvatar(name, img.getAttribute("width"), color);
  65. img.removeAttribute("avatar");
  66. img.setAttribute("alt", name);
  67. }
  68. );
  69. };
  70. export default LetterAvatar;