How Batch Avatar Generation Works in Vue Color Avatar
Vue Color Avatar generates a batch of unique avatars by creating a deduplicated pool of configuration objects, rendering them in a modal, and providing individual or bulk ZIP download capabilities using html2canvas and JSZip.
The vue-color-avatar library provides a powerful batch avatar generation feature that allows users to create multiple unique avatars simultaneously. This functionality is implemented through a three-stage pipeline that ensures uniqueness via cryptographic hashing and provides flexible export options. Understanding how batch avatar generation works reveals the architectural patterns used for deduplication, lazy loading, and client-side file generation.
The Three-Stage Batch Generation Pipeline
The batch generation process follows a clear pipeline: creating unique configurations, rendering them in the DOM, and exporting them as image files.
Stage 1: Creating a Deduplicated Pool of Avatar Options
The process begins in src/App.vue with the generateMultiple async function (lines 41‑66). When a user clicks the "Download multiple" button, this function generates a pool of unique avatar configurations.
The function repeatedly calls getRandomAvatarOption from src/utils/index.ts to create random configurations. To prevent duplicates, it uses the object‑hash library to generate SHA‑1 hashes of each AvatarOption object. These hashes serve as keys in a Map data structure, providing O(1) lookup time to detect collisions.
If a generated option's hash already exists in the Map, the loop retries until a unique configuration is found. Once the requested count is reached (defaulting to 30 avatars), the Map values are converted to an array and stored in the reactive avatarList ref.
Stage 2: Rendering the Batch in a Modal
Once avatarList is populated, the BatchDownloadModal.vue component (lines 34‑46) receives the array via the :avatar-list prop. The modal becomes visible based on the avatarListVisible computed property, which checks the list length.
Inside the modal, a v‑for loop iterates over the avatar options, mounting a <VueColorAvatar> component for each entry. Each avatar container receives a deterministic DOM id (avatar-${i}) based on its index, enabling precise targeting during the export phase.
Stage 3: Exporting Avatars via html2canvas and JSZip
The export functionality supports both individual and batch downloads, implemented in BatchDownloadModal.vue (lines 77‑131).
Single downloads use the handleDownload function (lines 77‑95). This function selects the DOM element by its id, invokes html2canvas to rasterize the SVG avatar with a transparent background, converts the canvas to a PNG data URL, and triggers a download via a programmatically created anchor element.
Batch downloads use the make function (lines 98‑131). This function dynamically imports html2canvas and JSZip to minimize initial bundle size. It loops through all avatar DOM nodes, rasterizes each one, and adds the base64 PNG data to a JSZip instance with sequential filenames (1.png, 2.png, etc.).
After processing all avatars, jsZip.generateAsync({ type: 'base64' }) creates the ZIP archive. The function then generates a data URL with the MIME type application/zip and triggers the download, saving all avatars as a single compressed file.
Key Implementation Details
Hash-Based Deduplication Strategy
The uniqueness guarantee relies on object‑hash with SHA‑1 hashing. Each AvatarOption object is serialized and hashed to create a hashKey. The Map data structure stores these keys with the option objects as values, providing efficient collision detection during the generation loop.
Lazy Loading Heavy Dependencies
Both html2canvas and jszip are imported dynamically using import() statements inside the download functions. This pattern ensures these substantial libraries are only loaded when the user initiates a download action, keeping the initial application bundle lightweight.
State Management Integration
The batch generation system integrates with the application's central state through the useAvatarOption composable in src/hooks/useAvatarOption.ts. This composable connects to store.history.present, allowing the batch generator to access the current avatar configuration as a baseline while creating random variations.
Code Examples
Programmatically Trigger Batch Generation
You can trigger batch generation programmatically from any component with access to the application instance:
import { getCurrentInstance } from 'vue'
// Inside any component setup()
const { proxy } = getCurrentInstance()!
proxy.generateMultiple?.(30) // generate 30 unique avatars
This invokes the generateMultiple method defined in src/App.vue (lines 41‑66).
Rendering a Custom Batch Modal
To render a batch of avatars in your own component:
<template>
<BatchDownloadModal :visible="true" :avatar-list="myAvatars" />
</template>
<script setup lang="ts">
import BatchDownloadModal from '@/components/Modal/BatchDownloadModal.vue'
import type { AvatarOption } from '@/types'
const myAvatars: AvatarOption[] = [
/* …populate with options from getRandomAvatarOption() … */
]
</script>
The modal expects an array of AvatarOption objects as defined in the prop definition in BatchDownloadModal.vue (lines 65‑66).
Manual ZIP Creation Logic
To implement the same batch download logic manually:
import html2canvas from 'html2canvas'
import JSZip from 'jszip'
async function zipAvatars(list: AvatarOption[]) {
const zip = new JSZip()
for (let i = 0; i < list.length; i++) {
const el = document.querySelector(`#avatar-${i}`) as HTMLElement
const canvas = await html2canvas(el, { backgroundColor: null })
const dataUrl = canvas.toDataURL().replace('data:image/png;base64,', '')
zip.file(`${i + 1}.png`, dataUrl, { base64: true })
}
const base64 = await zip.generateAsync({ type: 'base64' })
const a = document.createElement('a')
a.href = `data:application/zip;base64,${base64}`
a.download = 'avatars.zip'
a.click()
}
This mirrors the make() function in BatchDownloadModal.vue (lines 98‑131).
Summary
- Batch avatar generation in vue-color-avatar follows a three-stage pipeline: configuration generation, modal rendering, and export.
- Uniqueness is guaranteed through SHA‑1 hashing of
AvatarOptionobjects using theobject-hashlibrary, with collision detection via aMapdata structure. - Lazy loading of
html2canvasandjszipkeeps the initial bundle small, loading these libraries only when download actions are triggered. - Dual export modes support individual PNG downloads via
handleDownloadand bulk ZIP archives via themakefunction, both rasterizing SVG avatars from the DOM. - State integration occurs through the
useAvatarOptioncomposable, connecting batch generation to the central Vue store.
Frequently Asked Questions
How does vue-color-avatar ensure unique avatars in a batch?
The system uses hash-based deduplication during the generation phase. Each random AvatarOption object is serialized and hashed using the object-hash library with SHA‑1. These hashes are stored as keys in a Map structure, and any generated option with a duplicate hash is discarded and regenerated. This guarantees that every avatar in the final batch has a unique configuration.
What libraries are used for downloading avatars?
The batch download feature relies on two primary libraries: html2canvas for rasterizing the SVG-based avatars into PNG images, and JSZip for packaging multiple images into a single ZIP archive. Both libraries are loaded dynamically using import() only when a download is initiated, minimizing the initial application bundle size.
Can I customize the number of avatars generated in a batch?
Yes, the batch size is configurable through the generateMultiple method defined in src/App.vue. While the default implementation generates 30 avatars (5 × 6), you can pass any integer value when calling the method programmatically via proxy.generateMultiple?.(count). The deduplication logic will continue generating until it reaches the requested count of unique configurations.
Is the batch generation feature available programmatically?
Yes, the batch generation functionality is exposed through the application instance's generateMultiple method. Components can access this via Vue's getCurrentInstance() and the proxy object. This allows developers to trigger batch generation from custom UI elements or automated workflows, after which the avatarList reactive ref populates and automatically displays the BatchDownloadModal component.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →