multiavatar 是一个生成随机头像的开源项目,传入任意字符串生成头像,理论上可以生成 12 亿个不同的头像,可以在浏览器、Node.js 等环境下使用;
const multiavatar = require("@multiavatar/multiavatar");
更多传入任意字符生成 svg 头像的项目:
vercel/avatar 生成头像的代码:
const color = require("tinycolor2");
function djb2(str) {
let hash = 5381;
for (let i = 0; i < str.length; i++) {
hash = (hash << 5) + hash + str.charCodeAt(i);
}
return hash;
}
function generateGradient(username) {
const c1 = color({ h: djb2(username) % 360, s: 0.95, l: 0.5 });
const second = c1.triad()[1].toHexString();
return {
fromColor: c1.toHexString(),
toColor: second,
};
}
const gradient = generateGradient("username" || Math.random() + "");
const size = 120;
const avatar = `<svg
width="${size}"
height="${size}"
viewBox="0 0 ${size} ${size}"
version="1.1"
xmlns="http://www.w3.org/2000/svg"
>
<g>
<defs>
<linearGradient id="gradient" x1="0" y1="0" x2="1" y2="1">
<stop offset="0%" stop-color="${gradient.fromColor}" />
<stop offset="100%" stop-color="${gradient.toColor}" />
</linearGradient>
</defs>
<rect fill="url(#gradient)" x="0" y="0" width="${size}" height="${size}" />
</g>
</svg>`;
以下三个头像项目出同一位作者,但这三个项目只是随机生成头像,而不是根据某个字符串生成头像:
还有这个:Big Heads