minidenticons

repository·main·Indexed 20 days ago

https://github.com/laurentpayot/minidenticons

A lightweight, dependency-free SVG identicon generator for creating unique pixelated avatars from strings. Version 4.2.1 supports both a <minidenticon-svg> custom element for browser use and a minidenticon() function for programmatic SVG generation on the client or server (NodeJS 15.14.0+). It includes options to customize saturation and lightness, and supports custom hashing functions.

Tokens
1.7K
Snippets
8
Records
8
Agent score
20%

What's inside minidenticons

  1. Style minidenticon-svg custom elements

    main

    The custom element renders an SVG that expands to fill its container. The background is transparent, and there is built-in white space around the colored matrix to support uncropped circular avatars.

    To create a circular avatar, target the svg inside the custom element:

    minidenticon-svg svg {
      border-radius: 50%;
      background-color: grey;
      height: 48px;
      width: 48px;
    }

    You can also adjust the visual theme using the saturation and lightness attributes on the element (values between 0 and 100).

    <minidenticon-svg username="laurent" saturation="60" lightness="50"></minidenticon-svg>
  2. Install and use Minidenticons in NodeJS

    main

    Minidenticons supports NodeJS (version 15.14.0 or higher).

    1. Install via npm:
    npm install minidenticons
    1. Import the function:
    import { minidenticon } from 'minidenticons'

    When bundling for the browser from a NodeJS environment, you can tree-shake minidenticonSvg to keep your bundle size minimal.

  3. Use the minidenticon-svg custom element

    main

    You can use the included custom element to render identicons directly in the browser using HTML. This method is memoized (cached in memory) for performance.

    1. Import the minidenticonSvg custom element from minidenticons.min.js via an ES module script.
    2. Use the <minidenticon-svg> tag and provide a username attribute.

    Note: The closing tag </minidenticon-svg> is required.

    <script type="module">
      import { minidenticonSvg } from 'https://cdn.jsdelivr.net/npm/minidenticons@4.2.1/minidenticons.min.js'
    </script>
    
    <minidenticon-svg username="laurent"></minidenticon-svg>
  4. Generate identicons with Workbox Service Workers

    main

    You can use Minidenticons within a Workbox service worker to intercept requests for SVG files and generate them on-the-fly, allowing for efficient caching.

    import { minidenticon } from 'minidenticons'
    import { registerRoute } from 'workbox-routing'
    
    registerRoute(
      /minidenticons\/[^\/]+\.svg$/,
      async ({ url }) => {
        const username = url.pathname.match(/([^\/]+\.svg$)/)[1]
        return new Response(
          minidenticon(username),
          { headers: { "Content-Type": "image/svg+xml", "Cache-Control": "max-age=31536000" } }
        )
      }
    )
  5. Implement Minidenticons in React

    main

    To use Minidenticons in React, it is recommended to wrap the minidenticon() function in a component that uses useMemo to prevent unnecessary re-calculations and to convert the SVG string into a Data URI for use in an <img> tag.

    import { minidenticon } from 'minidenticons'
    import { useMemo } from 'react'
    
    const MinidenticonImg = ({ username, saturation, lightness, ...props }) => {
      const svgURI = useMemo(
        () => 'data:image/svg+xml;utf8,' + encodeURIComponent(minidenticon(username, saturation, lightness)),
        [username, saturation, lightness]
      )
      return (<img src={svgURI} alt={username} {...props} />)
    }
    
    // Usage
    <MinidenticonImg username="laurent" saturation="90" width="150" height="150" />
  6. Use the minidenticon() function for SVG generation

    main

    For programmatic access (client-side or server-side), use the minidenticon() function. This function returns a raw SVG string. Unlike the custom element, this function is not memoized.

    Signature: minidenticon(seed: string, saturation?: number|string, lightness?: number|string, hashFn?: (str: string) => number): string

    Parameters:

    • seed: A string used as the identifier (e.g., a username or hash).
    • saturation (optional): A number or string between 0 and 100 representing the percentage.
    • lightness (optional): A number or string between 0 and 100 representing the percentage.
    • hashFn (optional): A custom function that takes a string and returns a number. The last 15 bits of the integer part are used to draw the squares.
    // Example usage
    const svgString = minidenticon('laurent', 90, 45);
  7. Use the <minidenticon-svg> custom element

    main

    The minidenticon-svg custom element allows you to embed minidenticons directly into your HTML using web components. It automatically updates when its attributes change.

    Observed Attributes:

    • username (string): The seed used to generate the icon.
    • saturation (string/number): The HSL saturation percentage.
    • lightness (string/number): The HSL lightness percentage.

    Usage:

    <minidenticon-svg username="user123" saturation="90" lightness="40"></minidenticon-svg>
    <minidenticon-svg username="jdoe" saturation="95" lightness="45"></minidenticon-svg>
  8. Generate an SVG string with minidenticon()

    main

    The minidenticon() function generates a deterministic SVG string representing a unique icon based on a provided seed. It is useful for generating avatars in environments where you want full control over the output string (e.g., server-side rendering or manual DOM manipulation).

    Parameters:

    • seed (string): The input string used to generate the icon. If empty, no rects are generated.
    • saturation (number): The saturation percentage for the HSL color (defaults to 95).
    • lightness (number): The lightness percentage for the HSL color (defaults to 45).
    • hashFn (function): A custom hashing function that takes a string and returns a number. Defaults to simpleHash.
    import { minidenticon } from 'minidenticons';
    
    const svgString = minidenticon('my-username', 90, 50);
    // Use the string in your HTML
    document.body.innerHTML = svgString;