3333.html 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. <!DOCTYPE html>
  2. <html lang="zh-CN">
  3. <head>
  4. <meta charset="utf-8">
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6. <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport">
  7. <title></title>
  8. <!-- 引入jQuery -->
  9. <script type="text/javascript" src="js/jquery-1.11.3.js"></script>
  10. </head>
  11. <body>
  12. <!-- //图像显示容器,使用css控制样式,这里我写的圆形 -->
  13. <img src="" style="border-radius: 50%;" class="img-circle headImg" alt="User Image">
  14. <!-- //绘图元素 -->
  15. <canvas id="headImg" style="display:none"></canvas>
  16. <script type="text/javascript">
  17. $(function() {
  18. textToImg("代 码 狗", 100, "");
  19. });
  20. function textToImg(name, size, color) {
  21. //名字
  22. name = name || '';
  23. //图像大小
  24. size = size || 60;
  25. //背景颜色
  26. var colours = [
  27. "#1abc9c", "#2ecc71", "#3498db", "#9b59b6", "#34495e", "#16a085", "#27ae60", "#2980b9", "#8e44ad",
  28. "#2c3e50",
  29. "#f1c40f", "#e67e22", "#e74c3c", "#00bcd4", "#95a5a6", "#f39c12", "#d35400", "#c0392b", "#bdc3c7",
  30. "#7f8c8d"
  31. ],
  32. nameSplit = String(name).split(' '),
  33. initials, charIndex, colourIndex, canvas, context, dataURI;
  34. if (nameSplit.length == 1) {
  35. initials = nameSplit[0] ? nameSplit[0].charAt(0) : '?';
  36. } else {
  37. initials = nameSplit[0].charAt(0) + nameSplit[1].charAt(0);
  38. }
  39. //上面对名字进行一系列处理,下面找到绘图元素
  40. var canvas = document.getElementById('headImg');
  41. charIndex = (initials == '?' ? 72 : initials.charCodeAt(0)) - 64;
  42. colourIndex = charIndex % 20;
  43. //图像大小
  44. canvas.width = size;
  45. canvas.height = size;
  46. context = canvas.getContext("2d");
  47. //图像背景颜色
  48. context.fillStyle = color ? color : colours[colourIndex - 1];
  49. context.fillRect(0, 0, canvas.width, canvas.height);
  50. //字体大小
  51. context.font = Math.round(canvas.width / 2) + "px 'Microsoft Yahei'";
  52. context.textAlign = "center";
  53. //字体颜色
  54. context.fillStyle = "#FFF";
  55. // 绘制位置
  56. context.fillText(initials, size / 2, size / 1.5);
  57. //显示图像
  58. $('.headImg').attr('src', canvas.toDataURL("image/png"));
  59. };
  60. </script>
  61. </body>
  62. </html>