Last active
June 28, 2022 00:42
-
-
Save NuroDev/cf2e9a72b80125df592512554e62722d to your computer and use it in GitHub Desktop.
π Avatar Generator - Generate an SVG with a background color based on a hash of a provided string
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import { createHash } from "node:crypto"; | |
| const COLOR_NAMES = ["red", "green", "blue"]; | |
| const COLOR_SHADES = [500, 600, 700]; | |
| const COLORS: Record< | |
| typeof COLOR_NAMES[number], | |
| Record<typeof COLOR_SHADES[number], string> | |
| > = { | |
| red: { | |
| 500: "#ff455d", | |
| 600: "#dd243c", | |
| 700: "#c11027", | |
| }, | |
| green: { | |
| 500: "#27b648", | |
| 600: "#13862e", | |
| 700: "#19652a", | |
| }, | |
| blue: { | |
| 500: "#1e9de7", | |
| 600: "#0e73cc", | |
| 700: "#144eb6", | |
| }, | |
| }; | |
| interface GenerateSVGOptions { | |
| size?: number; | |
| } | |
| /** | |
| * Generate SVG | |
| * | |
| * @description Generates a new avatar SVG using a provided name string & assigns a background color based on a hash of the provided name | |
| * | |
| * @param {String} name - User's name | |
| * @param {Number} [options.size=24] - Size of the SVG in pixels **(Default: 24)** | |
| * | |
| * @returns {String} Generate SVG as a string | |
| */ | |
| export function generateSVG( | |
| name: string, | |
| options: GenerateSVGOptions = {} | |
| ): string { | |
| const { size = 24 } = options; | |
| const hash = createHash("sha1").update(name).digest("hex"); | |
| const [primaryColor, secondaryColor, tertiaryColor] = [...Array(3)].map( | |
| (_, i) => { | |
| const colorHash = hash.slice(i * 2, i * 2 + 2); | |
| const nameDecimal = parseInt(colorHash[0], 16); | |
| const colorName = COLOR_NAMES[nameDecimal % COLOR_NAMES.length]; | |
| const shadeDecimal = parseInt(colorHash[1], 16); | |
| const colorShade = COLOR_SHADES[shadeDecimal % COLOR_SHADES.length]; | |
| return COLORS[colorName][colorShade]; | |
| } | |
| ); | |
| return `<svg width="${size}" height="${size}" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><circle cx="12" cy="12" r="12" fill="url(#gradient)" transform="rotate(-90, 12, 12)" /><defs><radialGradient id="gradient" cx="0" cy="0" r="1" gradientUnits="userSpaceOnUse" gradientTransform="translate(20.5 2) rotate(127.694) scale(27.8029 21.5408)"><stop stop-color="${primaryColor}"/><stop offset="0.751919" stop-color="${secondaryColor}"/><stop offset="0.976459" stop-color="${tertiaryColor}"/></radialGradient></defs></svg>`.trim(); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment