使用 LetterAvatar 实现纯前端生成字母头像

#编程技术 2021-04-08 21:16:00 | 全文 852 字,阅读约需 2 分钟 | 加载中... 次浏览

👋 相关阅读


偶然发现码云上有个非常人性化的细节:会自动给没头像的用户生成一个昵称首字符的彩色头像,关键是打开控制台一看,发现这头像居然还是在前端实时生成的 这就很有意思了!

图片alt

以前知道 WordPress 有一款插件 WP First Letter Avatar 能实现类似的功能,但采用的是 php 在后端生成头像,使用起来不是很灵活。

仔细研究了码云的前端代码,发现它使用的是一个叫 LetterAvatar 的 JS 插件。它的原理是利用动态创建的 canvas 生成图像,然后显示在 img 标签中。具体的代码以及调用示例可以直接看下面的在线演示:https://mkblog.cn/blog/demo/LetterAvatar/

原作者:https://github.com/daolavi/LetterAvatar

使用方法:

页面添加以下 JS(页面需引用jquery):

/**
 * LetterAvatar
 * 
 * Artur Heinze
 * Create Letter avatar based on Initials
 * based on https://gist.github.com/leecrossley/6027780
 */
(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);

调用:

<img width="256" height="256" avatar="膨胀" color="#0D8ABC">

更新原生JS实现方法,无需jquery

function text_img(name, size, color) {
    var size = [size, size]
    let firstName = name.substring(1, 0);
    if(color==null){
        tranColor=(name)=>{
            var str = '';
            for (var i = 0; i < name.length; i++) {
                str += parseInt(name[i].charCodeAt(0), 10).toString(16);
            }
            return '#' + str.slice(1, 4);
        };
        color = this.tranColor(name);
    }
    let cvs = document.createElement("canvas");
    cvs.setAttribute('width', size[0]);
    cvs.setAttribute('height', size[1]);
    let ctx = cvs.getContext("2d");
    ctx.fillStyle = color;
    ctx.fillRect(0, 0, size[0], size[1]);
    ctx.fillStyle = 'rgb(255,255,255)';
    ctx.font = size[0] * 0.6 + "px Arial";
    ctx.textBaseline = "middle";
    ctx.textAlign = "center";
    ctx.fillText(firstName, size[0] / 2, size[1] / 2);
    return cvs.toDataURL('image/jpeg', 1);
}
var imgs = document.getElementsByTagName('img');
for(i=0;i<imgs.length;i++){
    name = imgs[i].getAttribute('avatar');
    color = imgs[i].getAttribute('color');
    imgs[i].src = text_img(name, imgs[i].getAttribute('width'), color);
}

使用:

<img width="50" avatar="Dao Lam" color="#0D8">
<img width="50" avatar="王图思睿">

不设置颜色默认获取名字的第一个字,转换成16进制文字颜色字符串,作为头像背景颜色;

via: 使用 LetterAvatar 实现纯前端生成字母头像 | 孟坤博客 https://mkblog.cn/1886/

Edit | Last updated on 2024-04-08 15:48:44




×