console
function generate() {
let val = document.getElementById('name').value || 'zoe';
let width = document.getElementById('width').value || 100;
let color = document.getElementById('color').value;
let fontSize = document.getElementById('fontSize').value || 38;
avatar(val, width, color, fontSize)
}
function avatar(name, width, color, fontSize) {
let colors = ['#ff0000', '#eb4310', '#f6941d', '#fbb417', '#ffff00', '#cdd541', '#99cc33', '#3f9337', '#219167', '#239676', '#24998d', '#1f9baa', '#0080ff', '#3366cc', '#333399', '#003366', '#800080', '#a1488e', '#c71585', '#bd2158'];
let canvas = document.getElementById('canvas');
let context = canvas.getContext('2d');
canvas.width = width;
canvas.height = width;
context.beginPath();
context.arc(width / 2, width / 2, width / 2 < width / 2 ? width / 2 : width / 2, 0, Math.PI * 2);
context.fillStyle = color || colors[Math.floor(Math.random() * colors.length)];
context.fill();
context.fillStyle = '#FFFFFF';
context.font = fontSize + 'px sans-serif';
context.textAlign = 'center';
context.textBaseline = "middle";
name = handleName(name);
context.fillText(name, width / 2, width / 2);
}
function handleName(name) {
if (escape(name).indexOf("%u") < 0) {
let names = name.split(' ')
if (names.length > 1) {
name = names[0].charAt(0).toUpperCase() + names[1].charAt(0).toUpperCase()
}
if (name.length > 3) {
name = name.substring(0, 3)
}
} else {
name = name.substr(-2, 2)
}
return name.toUpperCase();
}
<input placeholder='请输入您的姓名' id='name' />
<input placeholder='请输入头像直径,默认100' id='width' />
<input placeholder='请输入颜色,不填随机生成' id='color'/>
<input placeholder='请输入字号,默认38' id='fontSize'/>
<button onclick="generate()">生成</button>
<br>
<canvas id='canvas'></canvas>
*{margin: 0;padding: 0}
input,button,canvas{display: block;margin: 5px}
input{width: 250px}