text-to-avatar
v2.2.0
Published
A TypeScript package to generate avatar images
Readme
Text To Avatar
A TypeScript package to generate avatar images based on a user's name with customizable size, colors, and initials.
🚀 Installation
Install the package using npm:
npm install text-to-avataror using yarn:
yarn add text-to-avatar📖 Usage
Import the package and generate an avatar:
import { generateAvatarImage } from "text-to-avatar";
# Or
const { generateAvatarImage } = require("text-to-avatar")
const avatar = generateAvatarImage({ name: "John", size: 150, positions: [1, 2] });
console.log(avatar); // Base64 Image URL🔧 Options
The generateAvatarImage function accepts an object with the following properties:
| Parameter | Type | Default | Description |
| ----------- | ---------- | -------- | -------------------------------------------------- |
| name | string | 'test' | The name used to generate initials and color. |
| size | number | 100 | The size of the avatar (in pixels). |
| positions | number[] | [1, 2] | The positions of letters to extract from the name. |
Example Usages
Generate a 200px avatar for "Alice" using the first and third letters:
const avatar = generateAvatarImage({ name: "Alice", size: 200, positions: [1, 3] });
console.log(avatar); // Base64 Image URLGenerate a 100px avatar for "David" using the second and fourth letters:
const avatar = generateAvatarImage({ name: "David", size: 100, positions: [2, 4] });
console.log(avatar); // Base64 Image URL🎨 Font Support
You can use Google Fonts to customize the avatar font:
import { generateAvatarImage, addFont } from "text-to-avatar";
await addFont({ fontFamily: "Roboto", fontWeight: "700" });
const avatar = generateAvatarImage({ name: "John", size: 150, positions: [1, 2] });Options for addFont:
fontFamily string —
- Google Font family name -- ("Roboto")
fontWeight string —
- Font weight (optional)
- Default will be 400
Note: In browser, font is injected automatically via a tag. In Node.js, font is downloaded and registered with canvas.
🛠 How It Works
- Extracts initials from the specified
positionsin thename. - Generates a unique background color based on the
name. - Draws the initials in the center of the canvas with a white font.
- Returns a Base64 encoded image that can be used as an avatar.
📄 License
This project is licensed under the ISC License.
