UNPKG

@simplr-sh/avatar

Version:

Simplr Avatar is a simple package that allows you to create an avatar with a name or an image.

79 lines (76 loc) 2.65 kB
var __async = (__this, __arguments, generator) => { return new Promise((resolve, reject) => { var fulfilled = (value) => { try { step(generator.next(value)); } catch (e) { reject(e); } }; var rejected = (value) => { try { step(generator.throw(value)); } catch (e) { reject(e); } }; var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected); step((generator = generator.apply(__this, __arguments)).next()); }); }; // gradient.ts import color from "tinycolor2"; function hash(str) { return __async(this, null, function* () { let sum = 0; const buffer = yield crypto.subtle.digest( "SHA-1", new TextEncoder().encode(str) ); for (const n of new Uint8Array(buffer)) { sum += n; } return sum; }); } function hue(str) { return __async(this, null, function* () { const n = yield hash(str); return n % 360; }); } function generateGradient(username) { return __async(this, null, function* () { const h = yield hue(username); const c1 = color({ h, s: 0.95, l: 0.5 }); const second = c1.triad()[1].toHexString(); return { fromColor: c1.toHexString(), toColor: second }; }); } // index.ts function getAvatar(_0) { return __async(this, arguments, function* ({ name, text, size = 128, rounded = 0 }) { const gradient = yield generateGradient(name).catch((error) => { console.error("Error generating gradient:", error); return { fromColor: "#808080", toColor: "#C0C0C0" }; }); const svg = `<svg width="${size}" height="${size}" viewbox="0 0 ${size} ${size}" version="1.1" xmlns="http://www.w3.org/2000/svg" role="img" aria-label="${name} avatar"><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}" rx="${rounded}" ry="${rounded}"/>${text && getText({ text, size })}</g></svg>`; const base64SvgDataUri = `data:image/svg+xml;base64,${typeof Buffer !== "undefined" ? Buffer.from(svg).toString("base64") : btoa(svg)}`; return base64SvgDataUri; }); } function getText({ text, size }) { const fontSize = Math.max(size * 0.9 / text.length, size / 4); return `<text x="50%" y="50%" alignment-baseline="central" dominant-baseline="central" text-anchor="middle" fill="#fff" font-family="inherit" font-size="${fontSize}">${text}</text>`; } export { getAvatar };