Generating Avatars with createAvatar
Relevant source files
The following files were used as context for generating this wiki page:- packages/avatar/src/index.ts
- packages/avatar/src/core/index.ts
- packages/avatar/src/types.ts
- packages/avatar/src/utils/validation.ts
- packages/avatar/src/core/utils/svg.ts
- packages/avatar/src/open-peeps/index.ts
- packages/avatar/src/config/avatar.ts
- packages/avatar/src/utils/selectors.ts
- README.md
- packages/avatar/test/unit/index.test.ts
The @nextorders/avatar package provides a primary function, createAvatar, for the easy generation of SVG avatars. This system is designed to produce deterministic avatars based on a given seed string and a set of optional parameters. The visual style of the avatars is derived from the Open Peeps illustration set.
The core architecture separates the generic avatar creation logic from the specific styling rules. The main createAvatar function acts as a user-friendly facade that configures and calls a more generic createBaseAvatar engine. This engine, in turn, processes a style object (in this case, for open-peeps) to assemble the final SVG, applying various transformations and backgrounds.
Sources: README.md, packages/avatar/src/index.ts:15-18
High-Level Data Flow
The process of generating an avatar begins with a call to createAvatar and flows through several stages of validation, option building, and SVG construction before returning the final SVG string.
The following diagram illustrates the high-level data flow:
AvatarOptions Interface
The createAvatar function accepts a single options object that conforms to the AvatarOptions type. This interface defines the user-configurable parameters for avatar generation.
| Parameter | Type | Required | Description |
|---|---|---|---|
seed | string | Yes | A string used to seed the pseudo-random number generator, ensuring deterministic output. An error is thrown if not provided. |
gender | 'male' | 'female' | No | Specifies the gender, which influences the available avatar components. If not provided, a gender is chosen randomly. Validation ensures it is one of the two allowed values. |
clothing | 'amber' | 'green' | 'blue' | 'teal' | 'pink' | 'violet' | No | Sets a specific color for the clothing. If not provided, a default color is used. |
emotion | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | No | An integer from 1 to 10 that maps to a specific face emotion. If invalid or not provided, any face emotion can be chosen. Validation ensures the value is within the 1-10 range if provided. |
Sources: packages/avatar/src/types.ts:3-8, packages/avatar/src/utils/validation.ts:3-15
Option Processing
Before the core avatar generation begins, the user-provided AvatarOptions are processed and transformed into a more detailed internal options object.
buildOptions Function
The internal buildOptions function is responsible for this transformation. It merges several configuration sources:
SVG_CONFIG: Default SVG-level settings likesize,scale, andbackgroundType.AVATAR_CONFIG: Default avatar style settings likeaccessoriesProbabilityandskinColor.- Gender-specific Config: Based on the
genderoption, it merges eitherMALE_CONFIGorFEMALE_CONFIG, which defines the set of possibleheadandfacialHaircomponents. - User Options: The
seedis passed directly, andemotionandclothingare converted into specific component/color arrays by selector functions.
Sources: packages/avatar/src/index.ts:20-30, packages/avatar/src/config/avatar.ts:8-18, packages/avatar/src/utils/selectors.ts
Selector Functions
Helper functions translate high-level options into concrete choices for the open-peeps style.
| Function | Input (AvatarOptions) | Output | Description |
|---|---|---|---|
selectGenderConfig | gender | MALE_CONFIG or FEMALE_CONFIG | Selects the appropriate gender configuration object. If gender is undefined, it randomly chooses one. |
selectFaceEmotion | emotion | PossibleFace[] (Array of face names) | Maps a numeric emotion (1-10) to a specific face component name (e.g., smile, rage). If the emotion is invalid or omitted, it returns an array of all possible faces. |
selectClothingColor | clothing | string[] (Array of hex color codes) | Maps a clothing color name (e.g., 'blue') to its hex code. If omitted, it returns a default color. |
Sources: packages/avatar/src/utils/selectors.ts:7-29
Core Avatar Factory: createBaseAvatar
The createBaseAvatar function is the generic engine at the heart of the system. It is style-agnostic and responsible for orchestrating the entire SVG creation process based on a provided style object and the processed options.
The sequence of operations is as follows:
- A pseudo-random number generator (PRNG) is initialized with the
seedfrom the options. - The
style.create()method is called, passing the PRNG and options. This generates the core SVG body with avatar components. - Background colors and type (e.g.,
randomGradientLinear) are determined using the PRNG. - SVG transformations (
scale,flip,rotate,translateX,translateY) are applied to the SVG body. - A background layer is prepended to the SVG body.
- If a
radiusis specified, a clipping mask is applied to create rounded corners. - The final SVG attributes (like
viewBox,width,height) are assembled. - The complete
<svg>element is returned as part of a result object, which includes atoString()method.
Sources: packages/avatar/src/core/index.ts:10-69
This diagram shows the sequence of interactions managed by createBaseAvatar.
Sources: packages/avatar/src/core/index.ts
"Open Peeps" Style Implementation
The open-peeps module provides the concrete implementation of the Style interface. Its create function is responsible for generating the actual visual components of the avatar.
Component Assembly
The open-peeps/index.ts create function assembles the avatar from several component groups. It uses getComponents and getColors utility functions (which are not detailed in the provided files but whose purpose is clear) to select specific SVG parts based on the PRNG and options.
The final SVG body is constructed by layering these components:
- A base layer for skin and clothing.
head: The hair or headwear.face: The eyes, nose, and mouth, defining the expression.facialHair: Beards or moustaches.accessories: Glasses, eyepatches, etc.
// packages/avatar/src/open-peeps/index.ts:20-25
body: `<g fill-rule="evenodd" clip-rule="evenodd">...</g>
<g transform="matrix(.99789 0 0 1 156 62)">${components.head?.value(colors) ?? ''}</g>
<g transform="translate(315 248)">${components.face?.value(colors) ?? ''}</g>
<g transform="translate(279 400)">${components.facialHair?.value(colors) ?? ''}</g>
<g transform="translate(203 303)">${components.accessories?.value(colors) ?? ''}</g>`,
Each component group (e.g., face, accessories) is a collection of functions, where each function returns an SVG path string. For example, face.ts contains functions like smile, rage, and calm.
Sources: packages/avatar/src/open-peeps/index.ts:14-49, packages/avatar/src/open-peeps/components/face.ts, packages/avatar/src/open-peeps/components/accessories.ts, packages/avatar/src/open-peeps/components/facialHair.ts
Component Schema
The open-peeps/schema.ts file defines all possible string names for each component part, which are used for configuration and random selection.
| Component Category | Description |
|---|---|
accessories | Eyewear like glasses and sunglasses. |
face | The facial expression (eyes and mouth). |
facialHair | Various styles of moustaches and beards. |
head | Hairstyles, hats, and other head coverings. |
Sources: packages/avatar/src/open-peeps/schema.ts
SVG Manipulation Utilities
The core/utils/svg.ts file provides a suite of helper functions for post-processing the raw SVG body generated by the style.
| Function | Description |
|---|---|
addBackground | Prepends a <rect> to the SVG for a solid or gradient background. |
addScale | Wraps the SVG body in a <g> tag with a scale transform. |
addRotate | Wraps the SVG body in a <g> tag with a rotate transform. |
addFlip | Wraps the SVG body in a <g> tag to flip it horizontally. |
addTranslate | Wraps the SVG body in a <g> tag with a translate transform. |
addViewboxMask | Adds a <mask> to the SVG to clip the output, typically for creating rounded corners (radius option). |
createAttrString | Converts the attributes object into a string for the opening <svg> tag. |
Sources: packages/avatar/src/core/utils/svg.ts
Conclusion
The createAvatar feature is a well-structured system that combines a high-level, user-friendly API with a modular and extensible core. By separating the generic SVG generation engine from the specific "Open Peeps" style implementation, the library allows for flexible and deterministic avatar creation. The entire process is driven by a seed, ensuring that the same set of options will always produce the identical avatar, a key feature for user-specific but consistent visual representations.
Sources: packages/avatar/src/index.ts, packages/avatar/src/core/index.ts