Build an avatar creator with layered SVG and Stimulus

A while back I built a custom emoji composer using <canvas>. Fun project. But the canvas did all the work. It was responsible for the drawing surface, the drag logic and the export.
When I rebuilt the same idea as an avatar creator, I went for SVG instead. You pick a head, add some eyes, try a hat, then save the result as an image.
That cute face above is what I want to build today. 😊 A plain <svg>, a Stimulus controller and a folder of parts. No JS libraries except Stimulus.
As always, the code can be found on GitHub.
The HTML
Two elements: a <svg> for the preview and an empty <div> for the controls.
<div data-controller="avatar image-exporter" class="grid grid-cols-[300px_1fr] gap-8 max-w-5xl"> <div> <svg data-avatar-target="preview" viewBox="0 0 300 300" width="300" height="300" class="bg-white border border-gray-200 rounded-lg"></svg> <div class="grid grid-cols-2 mt-2 gap-x-3 *:w-full *:bg-gray-300 *:rounded-md"> <button data-action="click->avatar#reset">Reset</button> <button data-action="click->image-exporter#download">Save as image</button> </div> </div> <div data-avatar-target="controls" class="grid gap-4"></div> </div> The empty controls div is what the controller adds (more on why in a bit).
Why SVG instead of canvas?
The emoji composer drew glyphs onto a bitmap. Tracking where each one sat, converted mouse coordinates and cleared the surface before every redraw.
With this SVG version every part is real markup, so the browser handles layout and scaling. I keep the avatar as an object and turn it into an SVG string. When the object changes, rebuild a new string and drop it into the <svg>.
One win with this version: the avatar stays crisp at any size (because SVG!). With the emojis version this was not really possible.
Parts are data
Each part has its own file in app/javascript/avatar/parts/. Every option has a label and a render function that returns SVG:
const eyeball = (position) => `<circle cx="${position}" cy="152" r="8" fill="#fff" stroke="#2b2b2b" stroke-width="2"/>` + `<circle cx="${position}" cy="153" r="4" fill="#2b2b2b"/>` export const eyes = { round: { label: "Round", render: () => bothEyes(eyeball) }, happy: { label: "Happy", render: () => bothEyes(happyEye) }, wide: { label: "Wide", render: () => bothEyes(wideEye) }, sleepy: { label: "Sleepy", render: () => bothEyes(sleepyEye) } } To add a new pair of eyes, add an entry. The rest of the component finds it on its own.
Skin and hair color work the same: just carrying a hex value instead of a render function:
export const skin = { light: { label: "Light", color: "#ffe0c2" }, fair: { label: "Fair", color: "#f1c9a5" }, tan: { label: "Tan", color: "#d99b6c" }, brown: { label: "Brown", color: "#a96b3f" }, dark: { label: "Dark", color: "#6b4226" } } The layer order
[AD] Spinal CMS: Git-based CMS for static site generators
An avatar is a stack of parts. The order decides what sits on top. Ears go behind the head. The nose goes over the face. The hat goes over the hair.
Hair is a fun one, because it has two layers. The front fringe covers the forehead. Long hair also has a back mass that falls behind the head. So the renderer asks hair for both:
export function renderAvatar(avatar) { const context = { ...avatar, skin: skin[avatar.skin].color, hairColor: hairColor[avatar.hairColor].color } const hairstyle = hair[avatar.hairStyle] return [ hairstyle.back(context), ears[avatar.ears].render(context), head[avatar.head].render(context), hairstyle.front(context), eyes[avatar.eyes].render(context), nose[avatar.nose].render(context), mouth[avatar.mouth].render(context), hat[avatar.hat].render(context) ].join("") } Read it top to bottom and you can picture the face. The context carries the colors, so each part receives #f1c9a5 instead of the string "fair".
One object, full redraw
The controller adds the avatar as an object. Changing a part means copying that object with one new value, then re-rendering:
import { Controller } from "@hotwired/stimulus" import { renderAvatar } from "avatar/renderer" import { sections } from "avatar/sections" import { defaultAvatar } from "avatar/defaults" export default class extends Controller { static targets = ["preview", "controls"] #avatar = { ...defaultAvatar } connect() { this.#renderControls() this.#render() } setOption(event) { const { property, value } = event.currentTarget.dataset this.#avatar = { ...this.#avatar, [property]: value } this.#render() } reset() { this.#avatar = { ...defaultAvatar } this.#render() } } Controls that build themselves
One file adds every control on the page:
export const sections = [ { label: "Hair", controls: [ { property: "hairStyle", options: hair }, { property: "hairColor", options: hairColor, type: "color" } ] }, // head, eyes, nose, mouth, ears, hat, etc. ] The controller goes over that list and creates a button for each option. A type: "color" control becomes a swatch. Everything else is a labeled button:
if (control.type === "color") { button.className = "size-8 rounded-full border border-gray-300" button.style.background = option.color } else { button.className = "px-2 py-1 bg-white border border-gray-200 rounded-md text-sm hover:border-gray-400" button.textContent = option.label } Each button has a data-property and data-value.
Save as image
You cannot call toDataURL on an <svg> element. So I serialize the SVG to a string, load it into an Image, then draw that image onto a canvas:
const svg = this.element.querySelector("svg") const source = new XMLSerializer().serializeToString(svg) const image = new Image() image.onload = () => { const size = 600 const canvas = document.createElement("canvas") canvas.width = size canvas.height = size canvas.getContext("2d").drawImage(image, 0, 0, size, size) this.#trigger(this.#downloadLink(canvas.toDataURL("image/png"))) } image.src = "data:image/svg+xml;charset=utf-8," + encodeURIComponent(source) The canvas draws at 600×600, so the exported PNG comes out sharper than the on-screen preview. One thing to watch: any CSS the SVG relies on has to be inline. The serialized copy carries no external styles.
An that is it. Want more options? Adding a beard, glasses or nose ring can just be added to the parts folder. Simple as that.
Give it a shot and build something goofy. I want to see the hats, lipstick and monocles. 🎩💄🧐
原文:https://www.a8q9.cn/en/article/build-an-avatar-creator-with-layered-svg-and-stimulus-94defc.html