LetterAvatar 生成字母头像源码:
/**
* LetterAvatar
*
* Artur Heinze
* Create Letter avatar based on Initials
* based on https://gist.github.com/leecrossley/6027780
*/
示例(gitee):
这里将源码改为默认导出,可以直接封装进Vue或者自己的react项目中,作为utils函数。
/**
* 生成字母头像
* @param {*} name 需要生成的文字
* @param {*} size 大小
* @param {*} color 颜色
* @returns dataURI
*/
export default function generateLetterAvatar(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);
}
charIndex = (initials == '?' ? 72 : initials.charCodeAt(0)) - 64;
colourIndex = charIndex % 20;
canvas = document.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;
}
使用方法:
//导入
import generateLetterAvatar from '/@/plugins/letterAvatar/index';
//将src设置为generateLetterAvatar(生成的文字,大小,颜色)
<template>
<div class="flex justify-center">
<el-avatar :size="30" :src="generateLetterAvatar(name, 120)" />
</div>
</template>