首页 » 技术分享 » 实现纯前端生成字母头像

实现纯前端生成字母头像

 

纯前端字母头像插件

原作者 Github 地址

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>Avatar</title>
    <style>
        * {
            font-family: microsoft yahei;
            font-family: "Exo 2", "iconfont", "Trebuchet MS", "Helvetica", "Arial", 'PingFang SC', 'Hiragino Sans GB', 'STHeiti Light', 'Microsoft YaHei', 'SimHei', 'WenQuanYi Micro Hei', sans-serif;
            letter-spacing: 0.04em;
        }
        .container {
            max-width: 1000px;
        }
        h3 {
            margin-top: 35px;
            margin-bottom: 20px;
        }
        .round { border-radius: 50%; }
    </style>
</head>
<body>
<h3>使用方法</h3>
<pre>
<code>&lt;img width=&quot;256&quot; height=&quot;256&quot; avatar=&quot;Ban Xian&quot; color=&quot;#0D8ABC&quot;&gt;</code>
</pre>

<h3>在线演示</h3>
<img width="256" height="256" avatar="Ban Xian" color="#0D8ABC">

<div>
    <img width="100" height="100" avatar="默"> 
    <img width="100" height="100" avatar="认"> 
    <img width="100" height="100" avatar="头" color="#2c3e50"> 
    <img width="100" height="100" avatar="像" color="#c0392b"> 
</div>

<br>

<div>
    <img class="round" width="100" height="100" avatar="圆">
    <img class="round" width="100" height="100" avatar="角">
    <img class="round" width="100" height="100" avatar="示" color="#e67e22">
    <img class="round" width="100" height="100" avatar="例" color="#1abc9c">
    
</div>

<h3>插件完整代码</h3>
<pre>
/**
 * LetterAvatar
 * 
 * Artur Heinze
 * Create Letter avatar based on Initials
 * based on https://github.com/daolavi/LetterAvatar
 */
(function(w, d){
    function LetterAvatar (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);
        }
        if (w.devicePixelRatio) {
            size = (size * w.devicePixelRatio);
        }
            
        charIndex     = (initials == '?' ? 72 : initials.charCodeAt(0)) - 64;
        colourIndex   = charIndex % 20;
        canvas        = d.createElement('canvas');
        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);
        dataURI = canvas.toDataURL();
        canvas  = null;
        return dataURI;
    };
    
    LetterAvatar.transform = function() {
        Array.prototype.forEach.call(d.querySelectorAll('img[avatar]'), function(img, name, color) {
            name = img.getAttribute('avatar');
            color = img.getAttribute('color');
            img.src = LetterAvatar(name, img.getAttribute('width'), color);
            img.removeAttribute('avatar');
            img.setAttribute('alt', name);
        });
    };
    // AMD support
    if (typeof define === 'function' && define.amd) {
        
        define(function () { return LetterAvatar; });
    
    // CommonJS and Node.js module support.
    } else if (typeof exports !== 'undefined') {
        
        // Support Node.js specific `module.exports` (which can be a function)
        if (typeof module != 'undefined' && module.exports) {
            exports = module.exports = LetterAvatar;
        }
        // But always support CommonJS module 1.1.1 spec (`exports` cannot be a function)
        exports.LetterAvatar = LetterAvatar;
    } else {
        
        window.LetterAvatar = LetterAvatar;
        d.addEventListener('DOMContentLoaded', function(event) {
            LetterAvatar.transform();
        });
    }
})(window, document);
</pre>

<h3>修改为仅绘制一个字符作为头像 过滤 emoji</h3>
<pre>
(function (w, d) {
    window.LetterAvatar = function (name, size, color) {
        name = name || '';
        size = size || 60;
        var colours = [
                "#1abc9c", "#2ecc71", "#3498db", "#9b59b6", "#34495e", "#16a085", "#27ae60", "#2980b9", "#8e44ad", "#2c3e50",
                "#f1c40f", "#e67e22", "#e74c3c", "#ecf0f1", "#95a5a6", "#f39c12", "#d35400", "#c0392b", "#bdc3c7", "#7f8c8d"
            ],
            initials, charIndex, colourIndex, canvas, context, dataURI;
        
        initials = String(name);
        initials = initials.replace(/\uD83C[\uDF00-\uDFFF]|\uD83D[\uDC00-\uDE4F]/g, "");    // 去除 emoji
        initials = initials? initials.charAt(0): '?';
        
        if (w.devicePixelRatio) {
            size = (size * w.devicePixelRatio);
        }

        charIndex = (initials == '?' ? 72 : initials.charCodeAt(0)) - 64;
        colourIndex = charIndex % colours.length;
        canvas = d.createElement('canvas');
        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);
        dataURI = canvas.toDataURL();
        canvas = null;
        return dataURI;
    };
})(window, document);
</pre>
<script>
/**
 * LetterAvatar
 * 
 * Artur Heinze
 * Create Letter avatar based on Initials
 * based on https://github.com/daolavi/LetterAvatar
 */
(function(w, d){
    function LetterAvatar (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);
        }
        if (w.devicePixelRatio) {
            size = (size * w.devicePixelRatio);
        }
            
        charIndex     = (initials == '?' ? 72 : initials.charCodeAt(0)) - 64;
        colourIndex   = charIndex % 20;
        canvas        = d.createElement('canvas');
        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);
        dataURI = canvas.toDataURL();
        canvas  = null;
        return dataURI;
    };
    LetterAvatar.transform = function() {
        Array.prototype.forEach.call(d.querySelectorAll('img[avatar]'), function(img, name, color) {
            name = img.getAttribute('avatar');
            color = img.getAttribute('color');
            img.src = LetterAvatar(name, img.getAttribute('width'), color);
            img.removeAttribute('avatar');
            img.setAttribute('alt', name);
        });
    };
    // AMD support
    if (typeof define === 'function' && define.amd) {
        
        define(function () { return LetterAvatar; });
    
    // CommonJS and Node.js module support.
    } else if (typeof exports !== 'undefined') {
        
        // Support Node.js specific `module.exports` (which can be a function)
        if (typeof module != 'undefined' && module.exports) {
            exports = module.exports = LetterAvatar;
        }
        // But always support CommonJS module 1.1.1 spec (`exports` cannot be a function)
        exports.LetterAvatar = LetterAvatar;
    } else {
        
        window.LetterAvatar = LetterAvatar;
        d.addEventListener('DOMContentLoaded', function(event) {
            LetterAvatar.transform();
        });
    }
})(window, document);
</script>
</body>
</html>

转载自原文链接, 如需删除请联系管理员。

原文链接:实现纯前端生成字母头像,转载请注明来源!

0