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