Skip to content

Turn one illustration into an animated 2D mesh avatar with a coding agent and a local editor

Add a <mesh-avatar> custom element for embedding avatars

shinshin865cec24b3d622
diff --git a/.changeset/embed-element.md b/.changeset/embed-element.md
new file mode 100644
index 0000000..d2b0bf7
--- /dev/null
+++ b/.changeset/embed-element.md
@@ -0,0 +1,5 @@
+---
+'mesh-avatar-element': minor
+---
+
+Add a custom HTML element and standalone browser bundle for embedding mesh avatars.
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index e9164b8..f4d9961 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -40,12 +40,18 @@ jobs:
- name: Build runtime
run: npm run build:runtime
+ - name: Build embed element
+ run: npm run build:element
+
- name: Build landing page
run: npm run build:site
- name: Check runtime package contents
run: npm pack --dry-run -w mesh-avatar
+ - name: Check embed element package contents
+ run: npm pack --dry-run -w mesh-avatar-element
+
- name: Check the setup command package
run: npm pack --dry-run -w create-mesh-avatar-studio
diff --git a/AGENTS.md b/AGENTS.md
index 789731c..aaafddf 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -18,6 +18,7 @@ npm run lint
npm test
npm run build
npm run build:runtime
+npm run build:element
npm run e2e
uv run --with numpy --with pillow --with opencv-python-headless tools/test_build_layers.py
uv run tools/test_agent_tools.py
diff --git a/e2e/embed-element.spec.ts b/e2e/embed-element.spec.ts
new file mode 100644
index 0000000..c81df6e
--- /dev/null
+++ b/e2e/embed-element.spec.ts
@@ -0,0 +1,165 @@
+import { expect, test, type Page } from '@playwright/test';
+import { readFile } from 'node:fs/promises';
+import { PNG } from 'pngjs';
+import type { MeshAvatarElement } from '../packages/element/src/index';
+import { samplePresent, sampleSkipReason } from './sample';
+
+const sample = `http://127.0.0.1:${process.env.PLAYWRIGHT_SITE_PORT ?? 5174}/mesh-avatar-studio/miko.mavatar`;
+const defaultSrc = 'https://shinshin86.github.io/mesh-avatar-studio/miko.mavatar';
+const outside = new WeakMap<Page, string[]>();
+
+test.beforeEach(async ({ context, page }) => {
+ test.skip(!samplePresent, sampleSkipReason);
+ const requests: string[] = [];
+ outside.set(page, requests);
+ await context.route('**/*', route => {
+ const url = route.request().url();
+ if (url === defaultSrc) return route.fetch({ url: sample }).then(response => route.fulfill({ response }));
+ if (new URL(url).hostname !== '127.0.0.1') {
+ requests.push(url);
+ return route.abort();
+ }
+ return route.continue();
+ });
+});
+test.afterEach(({ page }) => { expect(outside.get(page) ?? []).toEqual([]); });
+
+async function open(page: Page) {
+ await page.goto('/e2e/fixtures/embed.html');
+ await expect.poll(() => page.evaluate(() => document.querySelector('mesh-avatar')?.avatar !== null &&
+ !!document.querySelector('mesh-avatar')?.avatar)).toBe(true);
+ await expect.poll(() => page.evaluate(() => Reflect.get(window, 'loads'))).toBe(1);
+}
+async function drawn(page: Page) {
+ const png = PNG.sync.read(await page.locator('mesh-avatar canvas').screenshot({ omitBackground: true }));
+ expect(png.data.some((value, index) => index % 4 === 3 && value > 0)).toBe(true);
+}
+
+test('default sample renders, emits load and follows expression attributes', async ({ page }) => {
+ await open(page);
+ expect(await page.evaluate(async () => {
+ const el = document.querySelector('mesh-avatar')!;
+ return await el.ready === el.avatar && el.avatar === Reflect.get(window, 'loadedAvatar');
+ })).toBe(true);
+ await drawn(page);
+ expect(await page.evaluate(() => document.querySelector('mesh-avatar')!.avatar!.getExpression().name)).toBe('smile');
+ await page.locator('mesh-avatar').evaluate(el => el.setAttribute('expression', 'wink'));
+ expect(await page.evaluate(() => document.querySelector('mesh-avatar')!.avatar!.getExpression().name)).toBe('wink');
+ await page.screenshot({ path: 'test-results/embed-element.png' });
+});
+
+test('switching src replaces ready and destroys the old avatar; failed loads emit errors and recover', async ({ page }) => {
+ const errors: string[] = [];
+ page.on('pageerror', error => errors.push(error.message));
+ await open(page);
+ expect(await page.evaluate(async src => {
+ const el = document.querySelector('mesh-avatar')!;
+ const old = el.avatar!, ready = el.ready;
+ let destroyed = 0;
+ const destroy = old.destroy.bind(old);
+ old.destroy = () => { destroyed++; destroy(); };
+ el.src = src;
+ const current = el.ready;
+ const avatar = await current;
+ return ready !== current && avatar !== old && el.avatar === avatar && destroyed === 1;
+ }, sample + '?replacement')).toBe(true);
+ for (const src of ['/missing-avatar.mavatar', '/broken-avatar.mavatar']) {
+ await page.route('**' + src, route => route.fulfill({ status: src.includes('missing') ? 404 : 200, body: 'broken' }));
+ const previous = await page.evaluate(() => Reflect.get(window, 'errors'));
+ await page.locator('mesh-avatar').evaluate((el, src) => { (el as MeshAvatarElement).src = src; }, src);
+ await expect.poll(() => page.evaluate(() => Reflect.get(window, 'errors'))).toBe(previous + 1);
+ expect(await page.evaluate(async () => {
+ try { await document.querySelector('mesh-avatar')!.ready; return false; } catch { return true; }
+ })).toBe(true);
+ }
+ await page.locator('mesh-avatar').evaluate((el, src) => { (el as MeshAvatarElement).src = src; }, sample);
+ await expect.poll(() => page.evaluate(() => !!document.querySelector('mesh-avatar')!.avatar)).toBe(true);
+ expect(errors).toEqual([]);
+});
+
+test('offscreen and paused elements stop advancing and resume on return', async ({ page }) => {
+ await open(page);
+ await page.evaluate(() => {
+ const avatar = document.querySelector('mesh-avatar')!.avatar!;
+ const advance = avatar.advance.bind(avatar);
+ Reflect.set(window, 'embedFrames', 0);
+ avatar.advance = (...args) => { Reflect.set(window, 'embedFrames', Reflect.get(window, 'embedFrames') + 1); advance(...args); };
+ });
+ const frames = () => page.evaluate(() => Reflect.get(window, 'embedFrames') as number);
+ const resumes = async () => { const count = await frames(); await expect.poll(frames).toBeGreaterThan(count); };
+ const stops = async () => {
+ // Allow the IntersectionObserver or pending animation frame to settle.
+ await page.waitForTimeout(200);
+ const count = await frames();
+ await page.waitForTimeout(250);
+ expect(await frames()).toBe(count);
+ };
+ await resumes();
+ await page.evaluate(() => window.scrollTo(0, document.body.scrollHeight));
+ await stops();
+ await page.evaluate(() => window.scrollTo(0, 0));
+ await resumes();
+ await page.locator('mesh-avatar').evaluate(el => el.setAttribute('paused', ''));
+ await stops();
+ await page.locator('mesh-avatar').evaluate(el => el.removeAttribute('paused'));
+ await resumes();
+});
+
+test('moving preserves the avatar; removal destroys it and reconnecting reloads it', async ({ page }) => {
+ await open(page);
+ expect(await page.evaluate(async () => {
+ const el = document.querySelector('mesh-avatar')!, avatar = el.avatar;
+ document.querySelector('#second')!.appendChild(el);
+ await Promise.resolve();
+ return el.avatar === avatar;
+ })).toBe(true);
+ expect(await page.evaluate(() => Reflect.get(window, 'loads'))).toBe(1);
+ expect(await page.evaluate(async () => {
+ const el = document.querySelector('mesh-avatar')!, old = el.avatar!;
+ let destroyed = 0;
+ const destroy = old.destroy.bind(old);
+ old.destroy = () => { destroyed++; destroy(); };
+ el.remove();
+ await Promise.resolve();
+ const unloaded = el.avatar === null && destroyed === 1;
+ document.querySelector('#first')!.appendChild(el);
+ return unloaded && await el.ready !== old;
+ })).toBe(true);
+ await expect.poll(() => page.evaluate(() => Reflect.get(window, 'loads'))).toBe(2);
+});
+
+test('standalone bundle renders with one module script and no dev-server transformation', async ({ page }) => {
+ const bundle = await readFile(new URL('../packages/element/dist/standalone.js', import.meta.url)).catch(error => {
+ if (error.code === 'ENOENT') {
+ throw new Error('Standalone bundle is missing. Run `npm run build:element` before running this test.', { cause: error });
+ }
+ throw error;
+ });
+ await page.route('**/element-standalone.js', route => route.fulfill({ contentType: 'text/javascript', body: bundle }));
+ await page.route('**/e2e/fixtures/embed.html', async route => {
+ const fixture = await readFile(new URL('./fixtures/embed.html', import.meta.url), 'utf8');
+ await route.fulfill({ contentType: 'text/html', body: fixture.replace('/packages/element/src/index.ts', '/element-standalone.js') });
+ });
+ await open(page);
+ expect(await page.evaluate(async () => await document.querySelector('mesh-avatar')!.ready ===
+ Reflect.get(window, 'loadedAvatar'))).toBe(true);
+ await drawn(page);
+});
+
+test('unknown expression warns once without throwing or changing the expression', async ({ page }) => {
+ const warnings: string[] = [], errors: string[] = [];
+ page.on('console', message => { if (message.type() === 'warning' && message.text().includes('<mesh-avatar>')) warnings.push(message.text()); });
+ page.on('pageerror', error => errors.push(error.message));
+ await open(page);
+ await page.locator('mesh-avatar').evaluate(el => {
+ el.setAttribute('expression', 'grin');
+ el.setAttribute('expression', 'smile');
+ el.setAttribute('expression', 'grin');
+ });
+ await expect.poll(() => warnings.length).toBe(1);
+ // Console events can arrive asynchronously; repeated values must not warn again.
+ await page.waitForTimeout(250);
+ expect(warnings).toEqual(['<mesh-avatar> ignores expression="grin".']);
+ expect(errors).toEqual([]);
+ expect(await page.evaluate(() => document.querySelector('mesh-avatar')!.avatar!.getExpression().name)).toBe('smile');
+});
diff --git a/e2e/fixtures/embed.html b/e2e/fixtures/embed.html
new file mode 100644
index 0000000..1589c76
--- /dev/null
+++ b/e2e/fixtures/embed.html
@@ -0,0 +1,21 @@
+<!doctype html>
+<html lang="en">
+<head>
+ <meta charset="utf-8">
+ <title>Mesh avatar element test</title>
+ <style>mesh-avatar { width: 300px; } #spacer { height: 2000px; }</style>
+</head>
+<body>
+ <div id="first"><mesh-avatar expression="smile"></mesh-avatar></div>
+ <div id="second"></div>
+ <div id="spacer"></div>
+ <script>
+ window.loads = 0;
+ window.errors = 0;
+ const el = document.querySelector('mesh-avatar');
+ el.addEventListener('load', event => { window.loads++; window.loadedAvatar = event.detail.avatar; });
+ el.addEventListener('error', () => { window.errors++; });
+ </script>
+ <script type="module" src="/packages/element/src/index.ts"></script>
+</body>
+</html>
diff --git a/package-lock.json b/package-lock.json
index 01f8094..0358ace 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -3742,6 +3742,10 @@
"resolved": "packages/runtime",
"link": true
},
+ "node_modules/mesh-avatar-element": {
+ "resolved": "packages/element",
+ "link": true
+ },
"node_modules/micromatch": {
"version": "4.0.8",
"resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.8.tgz",
@@ -4978,7 +4982,7 @@
}
},
"packages/create-mesh-avatar-studio": {
- "version": "0.0.0",
+ "version": "0.1.1",
"license": "MIT",
"bin": {
"create-mesh-avatar-studio": "index.mjs"
@@ -4987,9 +4991,17 @@
"node": ">=22.17"
}
},
+ "packages/element": {
+ "name": "mesh-avatar-element",
+ "version": "0.0.0",
+ "license": "MIT",
+ "dependencies": {
+ "mesh-avatar": "^0.2.1"
+ }
+ },
"packages/runtime": {
"name": "mesh-avatar",
- "version": "0.2.0",
+ "version": "0.2.1",
"license": "MIT",
"dependencies": {
"fflate": "^0.8.3"
diff --git a/package.json b/package.json
index f7d339b..f144e9f 100644
--- a/package.json
+++ b/package.json
@@ -11,9 +11,10 @@
"preview:site": "vite preview --config site/vite.config.ts",
"screenshots": "node tools/capture-readme-screenshots.mjs",
"test": "vitest run",
- "lint": "eslint src tests e2e tools/*.mjs packages/create-mesh-avatar-studio/*.mjs packages/runtime/src packages/runtime/tests packages/runtime/vite.config.ts packages/runtime/*.mjs site/src site/vite.config.ts",
+ "lint": "eslint src tests e2e tools/*.mjs packages/create-mesh-avatar-studio/*.mjs packages/runtime/src packages/runtime/tests packages/runtime/vite.config.ts packages/runtime/*.mjs packages/element/src packages/element/tests packages/element/vite.config.ts site/src site/vite.config.ts",
"build": "tsc --noEmit && vite build",
"build:runtime": "npm run build -w mesh-avatar",
+ "build:element": "npm run build -w mesh-avatar-element",
"changeset": "changeset",
"changeset:version": "changeset version",
"changeset:publish": "changeset publish",
diff --git a/packages/element/LICENSE b/packages/element/LICENSE
new file mode 100644
index 0000000..8b20d89
--- /dev/null
+++ b/packages/element/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2026 Yuki Shindo
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/packages/element/README.md b/packages/element/README.md
new file mode 100644
index 0000000..8791820
--- /dev/null
+++ b/packages/element/README.md
@@ -0,0 +1,218 @@
+# mesh-avatar-element
+
+Embed an animated 2D avatar with a `<mesh-avatar>` HTML element. Uses the [mesh-avatar](https://github.com/shinshin86/mesh-avatar-studio/tree/main/packages/runtime) WebGL runtime, with no framework required.
+
+<p align="center">
+ <img src="https://raw.githubusercontent.com/shinshin86/mesh-avatar-studio/main/docs/images/face-tracking.gif" width="400" alt="A Mesh Avatar Studio avatar following a face through a webcam">
+</p>
+
+## Getting started
+
+### CDN
+
+Add these two lines to your page to show the Miko sample:
+
+```html
+<script type="module" src="https://cdn.jsdelivr.net/npm/mesh-avatar-element@0/dist/standalone.js"></script>
+<mesh-avatar></mesh-avatar>
+```
+
+### npm
+
+```sh
+npm install mesh-avatar-element
+```
+
+Import once in your app's JavaScript:
+
+```js
+import 'mesh-avatar-element';
+```
+
+Then add `<mesh-avatar></mesh-avatar>` to your HTML.
+
+### Your own avatar
+
+Open your project in [Mesh Avatar Studio](https://github.com/shinshin86/mesh-avatar-studio) and choose **Export .mavatar**. Put the exported file on your site and set `src`:
+
+```html
+<mesh-avatar src="/avatars/character.mavatar" expression="smile"></mesh-avatar>
+```
+
+An unpacked avatar folder URL also works. Cross-origin assets need CORS headers.
+
+### Size
+
+The element defaults to `display: block; aspect-ratio: 3 / 4`. Set its width in your page's CSS; you can also override its height or aspect ratio. The background is transparent.
+
+```html
+<style>
+ mesh-avatar { width: min(100%, 320px); }
+</style>
+<mesh-avatar></mesh-avatar>
+```
+
+## Attributes
+
+| Attribute | Values | Default |
+| --- | --- | --- |
+| `src` | A `.mavatar` URL or avatar folder URL | [Miko on GitHub Pages](https://shinshin86.github.io/mesh-avatar-studio/miko.mavatar) |
+| `fit` | `contain`, `cover` | `contain` |
+| `expression` | `neutral`, `smile`, `shy`, `surprise`, `halfLidded`, `angry`, `sad`, `wink` | `neutral` |
+| `emotion` | `happy`, `sad`, `angry`, `surprised`, `relaxed`, `neutral` | Unset |
+| `paused` | Boolean attribute; presence pauses animation | Absent |
+| `no-idle` | Boolean attribute; presence disables automatic idle motion | Absent |
+| `label` | Accessible canvas label | `Avatar` |
+
+Attributes can be changed after loading. Changing `src` or `fit` destroys the current avatar and loads a new one. A failed load leaves the element empty; listen for `error` to show a fallback. Unknown expression, emotion or fit values warn once per attribute/value pair rather than throwing.
+
+## Properties, methods and events
+
+Wait for the custom element to be registered before accessing it from a separate script:
+
+```js
+await customElements.whenDefined('mesh-avatar');
+const el = document.querySelector('mesh-avatar');
+await el.ready;
+el.avatar.setExpression('smile');
+```
+
+| Property or method | Description |
+| --- | --- |
+| `avatar` | Loaded runtime avatar, or `null`. All [runtime methods](https://github.com/shinshin86/mesh-avatar-studio/tree/main/packages/runtime#drive-the-avatar) are available through `el.avatar`. |
+| `ready` | Promise resolving with the current avatar, rejecting on loading failure. A new load after completion creates a new promise; overlapping pending loads resolve with the latest avatar. |
+| `src`, `fit`, `expression`, `emotion`, `paused` | Properties reflecting their corresponding attributes. Use attributes for `no-idle` and `label`. |
+| `setVoiceLevel(value)` | Mouth opening from loudness, 0–1. Retains the value until loading finishes. |
+| `speak(text, options?)` | Calls `speakKana` after loading. Japanese text animates the mouth without generating audio. Options: `speed`, `loop`. |
+| `play(id)` | Plays a runtime motion after loading. Available IDs are in `el.avatar.motions`. |
+
+`speak` and `play` return promises; handle rejected promises if loading can fail.
+
+| Event | `event.detail` | When |
+| --- | --- | --- |
+| `load` | `{ avatar }` | Avatar loaded and ready |
+| `error` | `{ error }` | Loading failed |
+| `motion` | `{ id }` (string or `null`) | The runtime reports a motion change |
+
+Attach listeners directly to the element with `el.addEventListener('load', event => { /* … */ })`.
+Moving the element between parents in the same turn preserves the avatar. Removing it destroys the avatar; reconnecting it starts a new load.
+
+## Lip sync
+
+Each example below assumes the CDN script and a `<mesh-avatar>` element are on your page. Run JavaScript as a module.
+
+### Audio file or TTS audio
+
+Replace `/voice.mp3` with an audio file or a URL returned by your TTS service. Cross-origin audio needs CORS headers. Click the button to start playback.
+
+```html
+<button id="play-voice">Play voice</button>
+<script type="module">
+await customElements.whenDefined('mesh-avatar');
+const el = document.querySelector('mesh-avatar');
+await el.ready;
+const audio = new Audio();
+audio.crossOrigin = 'anonymous';
+audio.src = '/voice.mp3';
+const ctx = new AudioContext();
+const analyser = ctx.createAnalyser();
+ctx.createMediaElementSource(audio).connect(analyser);
+analyser.connect(ctx.destination);
+const data = new Float32Array(analyser.fftSize);
+function frame() {
+ if (audio.paused || audio.ended) {
+ el.avatar.setSpeaking(false);
+ el.setVoiceLevel(0);
+ return;
+ }
+ analyser.getFloatTimeDomainData(data);
+ el.setVoiceLevel(Math.min(1, Math.sqrt(data.reduce((s, v) => s + v * v, 0) / data.length) * 5));
+ requestAnimationFrame(frame);
+}
+document.querySelector('#play-voice').onclick = async () => {
+ await ctx.resume();
+ await audio.play();
+ el.avatar.setSpeaking(true);
+ frame();
+};
+</script>
+```
+
+### Microphone
+
+Start microphone capture from a user action. Microphone access requires HTTPS or localhost and the user's permission. The microphone is not connected to the speakers.
+
+```html
+<button id="mic">Start microphone</button>
+<script type="module">
+await customElements.whenDefined('mesh-avatar');
+const el = document.querySelector('mesh-avatar');
+await el.ready;
+let stop;
+document.querySelector('#mic').onclick = async event => {
+ if (stop) {
+ stop();
+ stop = null;
+ event.target.textContent = 'Start microphone';
+ return;
+ }
+ const ctx = new AudioContext();
+ await ctx.resume();
+ const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
+ const analyser = ctx.createAnalyser();
+ ctx.createMediaStreamSource(stream).connect(analyser);
+ const data = new Float32Array(analyser.fftSize);
+ let frameId;
+ el.avatar.setSpeaking(true);
+ const frame = () => {
+ analyser.getFloatTimeDomainData(data);
+ el.setVoiceLevel(Math.min(1, Math.sqrt(data.reduce((s, v) => s + v * v, 0) / data.length) * 5));
+ frameId = requestAnimationFrame(frame);
+ };
+ stop = () => {
+ cancelAnimationFrame(frameId);
+ stream.getTracks().forEach(t => t.stop());
+ void ctx.close();
+ el.avatar.setSpeaking(false);
+ el.setVoiceLevel(0);
+ };
+ frame();
+ event.target.textContent = 'Stop microphone';
+};
+</script>
+```
+
+### Text only
+
+This makes mouth shapes from Japanese text; it does not play or synthesize a voice.
+
+```html
+<button id="say">Animate speech</button>
+<script type="module">
+await customElements.whenDefined('mesh-avatar');
+const el = document.querySelector('mesh-avatar');
+await el.ready;
+document.querySelector('#say').onclick = () => el.speak('こんにちは');
+</script>
+```
+
+## Using the Miko sample
+
+Without `src`, Miko loads from Mesh Avatar Studio's GitHub Pages site. To host it yourself instead, save
+[the Miko archive](https://shinshin86.github.io/mesh-avatar-studio/miko.mavatar) as part of your site and point `src` at your copy.
+
+Miko © Yuki Shindo (AITuber OnAir). Follow the [Miko character guidelines](https://miko.aituberonair.com/#terms).
+Redistribution as part of an application or website is allowed; standalone distribution, asset collections and distribution primarily intended to provide the assets are not.
+Do not imply official affiliation or endorsement by Miko or AITuber OnAir, or claim ownership of the character or exclusive usage rights. See also the [sample asset terms](https://github.com/shinshin86/mesh-avatar-studio/blob/main/samples/miko-qipao/MIKO_ASSET_TERMS.md).
+
+## Notes
+
+- Requires WebGL2 in a browser.
+- Avoid placing many avatars on one page: browsers limit simultaneous WebGL contexts.
+- Animation pauses offscreen, while the tab is hidden, or when `paused` is present.
+- With `prefers-reduced-motion: reduce`, hair sway is reduced.
+- The npm entry point can be imported during server-side rendering, but rendering requires the browser.
+
+## License
+
+MIT. Miko's artwork is subject to the character guidelines above.
diff --git a/packages/element/package.json b/packages/element/package.json
new file mode 100644
index 0000000..b6e2446
--- /dev/null
+++ b/packages/element/package.json
@@ -0,0 +1,50 @@
+{
+ "name": "mesh-avatar-element",
+ "version": "0.0.0",
+ "type": "module",
+ "license": "MIT",
+ "description": "A <mesh-avatar> custom element: put a Mesh Avatar Studio avatar on any web page with one tag.",
+ "repository": {
+ "type": "git",
+ "url": "git+https://github.com/shinshin86/mesh-avatar-studio.git",
+ "directory": "packages/element"
+ },
+ "homepage": "https://github.com/shinshin86/mesh-avatar-studio/tree/main/packages/element",
+ "keywords": [
+ "avatar",
+ "2d",
+ "webgl",
+ "web-components",
+ "custom-element",
+ "vtuber",
+ "mesh-avatar"
+ ],
+ "sideEffects": [
+ "./dist/index.js",
+ "./dist/standalone.js"
+ ],
+ "types": "./dist/index.d.ts",
+ "files": [
+ "dist",
+ "README.md",
+ "LICENSE"
+ ],
+ "publishConfig": {
+ "access": "public",
+ "provenance": true
+ },
+ "scripts": {
+ "build": "vite build && vite build --mode standalone && tsc -p tsconfig.build.json",
+ "prepack": "npm run build"
+ },
+ "exports": {
+ ".": {
+ "types": "./dist/index.d.ts",
+ "import": "./dist/index.js"
+ },
+ "./standalone": "./dist/standalone.js"
+ },
+ "dependencies": {
+ "mesh-avatar": "^0.2.1"
+ }
+}
diff --git a/packages/element/src/attributes.ts b/packages/element/src/attributes.ts
new file mode 100644
index 0000000..bf5795d
--- /dev/null
+++ b/packages/element/src/attributes.ts
@@ -0,0 +1,54 @@
+import { LIVE_EXPRESSIONS, type LiveExpression } from 'mesh-avatar';
+
+/** Shown when the element has no `src`: the Miko sample published with the Mesh Avatar Studio site. */
+export const DEFAULT_SRC = 'https://shinshin86.github.io/mesh-avatar-studio/miko.mavatar';
+
+export const EMOTIONS = ['happy', 'sad', 'angry', 'surprised', 'relaxed', 'neutral'] as const;
+export type Emotion = typeof EMOTIONS[number];
+export type Fit = 'contain' | 'cover';
+
+/** Returns the expression, 'neutral' when the attribute is missing, or undefined when it is unknown. */
+export function parseExpression(value: string | null): LiveExpression | undefined {
+ if (value === null || value === '') return 'neutral';
+ return (LIVE_EXPRESSIONS as string[]).includes(value) ? value as LiveExpression : undefined;
+}
+
+/** Returns the emotion, null when the attribute is missing, or undefined when it is unknown. */
+export function parseEmotion(value: string | null): Emotion | null | undefined {
+ if (value === null || value === '') return null;
+ return (EMOTIONS as readonly string[]).includes(value) ? value as Emotion : undefined;
+}
+
+/** Returns the fit, 'contain' when the attribute is missing, or undefined when it is unknown. */
+export function parseFit(value: string | null): Fit | undefined {
+ if (value === null || value === '') return 'contain';
+ return value === 'contain' || value === 'cover' ? value : undefined;
+}
+
+/** Seconds since the previous frame, limited like the runtime's own loop. */
+export function frameSeconds(now: number, previous: number) {
+ return Math.min(0.05, Math.max(0.001, (now - previous) / 1000));
+}
+
+/**
+ * A promise for the avatar that is loading now. A load that starts before the previous one
+ * finished keeps the same pending promise, so callers waiting on it get the newest avatar.
+ */
+export class ReadySignal<T> {
+ promise!: Promise<T>;
+ #resolve!: (value: T) => void;
+ #reject!: (error: unknown) => void;
+ #settled = true;
+
+ /** Call when a load starts. */
+ start() {
+ if (!this.#settled) return;
+ this.#settled = false;
+ this.promise = new Promise<T>((resolve, reject) => { this.#resolve = resolve; this.#reject = reject; });
+ // Callers who never await `ready` should not see unhandled rejections.
+ this.promise.catch(() => {});
+ }
+
+ resolve(value: T) { if (!this.#settled) { this.#settled = true; this.#resolve(value); } }
+ reject(error: unknown) { if (!this.#settled) { this.#settled = true; this.#reject(error); } }
+}
diff --git a/packages/element/src/index.ts b/packages/element/src/index.ts
new file mode 100644
index 0000000..b7989d5
--- /dev/null
+++ b/packages/element/src/index.ts
@@ -0,0 +1,200 @@
+import { loadMeshAvatar, type MeshAvatar } from 'mesh-avatar';
+import { DEFAULT_SRC, frameSeconds, parseEmotion, parseExpression, parseFit, ReadySignal, type Fit } from './attributes.js';
+
+export { DEFAULT_SRC, EMOTIONS } from './attributes.js';
+export type { Emotion, Fit } from './attributes.js';
+export type { MeshAvatar, LiveExpression } from 'mesh-avatar';
+
+const STYLE = `
+:host { display: block; position: relative; aspect-ratio: 3 / 4; }
+:host([hidden]) { display: none; }
+canvas { display: block; width: 100%; height: 100%; }
+`;
+
+// Server-side rendering has no HTMLElement; the class is defined but never registered there.
+const Base = (typeof HTMLElement === 'undefined' ? class {} : HTMLElement) as typeof HTMLElement;
+
+/**
+ * `<mesh-avatar>`: shows a Mesh Avatar Studio avatar. Without `src` it shows the Miko sample.
+ * Animation pauses while the element is off screen, the tab is hidden or `paused` is set.
+ */
+export class MeshAvatarElement extends Base {
+ static observedAttributes = ['src', 'fit', 'expression', 'emotion', 'paused', 'no-idle', 'label'];
+
+ #canvas: HTMLCanvasElement;
+ #avatar: MeshAvatar | null = null;
+ #ready = new ReadySignal<MeshAvatar>();
+ #loadId = 0;
+ #loading = false;
+ #raf = 0;
+ #previous = 0;
+ #onScreen = true;
+ #observer: IntersectionObserver | null = null;
+ #voiceLevel: number | null = null;
+ #warned = new Set<string>();
+
+ constructor() {
+ super();
+ const root = this.attachShadow({ mode: 'open' });
+ const style = document.createElement('style');
+ style.textContent = STYLE;
+ this.#canvas = document.createElement('canvas');
+ this.#canvas.setAttribute('role', 'img');
+ this.#canvas.setAttribute('aria-label', 'Avatar');
+ root.append(style, this.#canvas);
+ this.#ready.start();
+ this.#canvas.addEventListener('webglcontextlost', event => { event.preventDefault(); this.#stopLoop(); });
+ this.#canvas.addEventListener('webglcontextrestored', () => this.#load());
+ }
+
+ /** The loaded runtime avatar, or null while loading. Every `mesh-avatar` method is available on it. */
+ get avatar() { return this.#avatar; }
+ /** Resolves with the avatar once the current `src` has loaded. */
+ get ready() { return this.#ready.promise; }
+
+ get src() { return this.getAttribute('src') ?? ''; }
+ set src(value: string) { this.setAttribute('src', value); }
+ get fit(): Fit { return parseFit(this.getAttribute('fit')) ?? 'contain'; }
+ set fit(value: Fit) { this.setAttribute('fit', value); }
+ get expression() { return this.getAttribute('expression') ?? 'neutral'; }
+ set expression(value: string) { this.setAttribute('expression', value); }
+ get emotion() { return this.getAttribute('emotion'); }
+ set emotion(value: string | null) { if (value === null) this.removeAttribute('emotion'); else this.setAttribute('emotion', value); }
+ get paused() { return this.hasAttribute('paused'); }
+ set paused(value: boolean) { this.toggleAttribute('paused', value); }
+
+ /** Mouth opening from the voice loudness, 0 to 1. Kept until the avatar loads. */
+ setVoiceLevel(value: number) {
+ this.#voiceLevel = value;
+ this.#avatar?.setVoiceLevel(value);
+ }
+
+ /** Moves the mouth to Japanese text without audio. Waits for the avatar to load. */
+ async speak(text: string, options?: { speed?: number; loop?: boolean }) {
+ (await this.ready).speakKana(text, options);
+ }
+
+ /** Plays a motion by id (see `avatar.motions`). Waits for the avatar to load. */
+ async play(id: string) {
+ (await this.ready).play(id);
+ }
+
+ connectedCallback() {
+ this.#observer ??= new IntersectionObserver(entries => {
+ this.#onScreen = entries.at(-1)?.isIntersecting ?? true;
+ this.#updateLoop();
+ });
+ this.#observer.observe(this);
+ document.addEventListener('visibilitychange', this.#updateLoop);
+ if (!this.#avatar && !this.#loading) this.#load();
+ else this.#updateLoop();
+ }
+
+ disconnectedCallback() {
+ this.#observer?.disconnect();
+ document.removeEventListener('visibilitychange', this.#updateLoop);
+ this.#stopLoop();
+ // Moving the element elsewhere in the page reconnects it at once; keep the avatar then.
+ queueMicrotask(() => { if (!this.isConnected) this.#unload(); });
+ }
+
+ attributeChangedCallback(name: string, old: string | null, value: string | null) {
+ if (old === value) return;
+ if (name === 'src' || name === 'fit') {
+ if (name === 'fit' && parseFit(value) === undefined) this.#warn(name, value);
+ if (this.isConnected) this.#load();
+ } else if (name === 'label') {
+ this.#canvas.setAttribute('aria-label', value || 'Avatar');
+ } else if (name === 'paused') {
+ this.#updateLoop();
+ } else if (this.#avatar) {
+ this.#apply(this.#avatar, name);
+ }
+ }
+
+ #apply(avatar: MeshAvatar, name: string) {
+ if (name === 'expression') {
+ const expression = parseExpression(this.getAttribute('expression'));
+ if (expression) avatar.setExpression(expression); else this.#warn(name, this.getAttribute(name));
+ } else if (name === 'emotion') {
+ const emotion = parseEmotion(this.getAttribute('emotion'));
+ if (emotion !== undefined) avatar.setEmotion(emotion); else this.#warn(name, this.getAttribute(name));
+ } else if (name === 'no-idle') {
+ avatar.setAutoIdle(!this.hasAttribute('no-idle'));
+ }
+ }
+
+ async #load() {
+ const id = ++this.#loadId;
+ this.#unload(false);
+ this.#loading = true;
+ this.#ready.start();
+ try {
+ const avatar = await loadMeshAvatar(this.#canvas, this.getAttribute('src') || DEFAULT_SRC, { manual: true, fit: this.fit });
+ if (id !== this.#loadId) { avatar.destroy(); return; }
+ this.#loading = false;
+ this.#avatar = avatar;
+ for (const name of ['expression', 'emotion', 'no-idle']) {
+ if (name !== 'emotion' || this.hasAttribute(name)) this.#apply(avatar, name);
+ }
+ if (this.#voiceLevel !== null) avatar.setVoiceLevel(this.#voiceLevel);
+ // Hair moves less for people who ask for reduced motion; the avatar itself still moves.
+ if (matchMedia('(prefers-reduced-motion: reduce)').matches) avatar.setSwayGain(0.5);
+ avatar.onMotion(motion => this.dispatchEvent(new CustomEvent('motion', { detail: { id: motion } })));
+ avatar.advance(0);
+ this.#ready.resolve(avatar);
+ this.dispatchEvent(new CustomEvent('load', { detail: { avatar } }));
+ this.#updateLoop();
+ } catch (error) {
+ if (id !== this.#loadId) return;
+ this.#loading = false;
+ this.#ready.reject(error);
+ this.dispatchEvent(new CustomEvent('error', { detail: { error } }));
+ }
+ }
+
+ /** Destroys the avatar. Without `cancel = false` it also abandons a load in progress. */
+ #unload(cancel = true) {
+ if (cancel) { this.#loadId++; this.#loading = false; }
+ this.#stopLoop();
+ this.#avatar?.destroy();
+ this.#avatar = null;
+ }
+
+ #updateLoop = () => {
+ const run = this.#avatar && this.isConnected && this.#onScreen && !document.hidden && !this.paused;
+ if (run && !this.#raf) {
+ this.#previous = performance.now();
+ this.#raf = requestAnimationFrame(this.#frame);
+ } else if (!run) {
+ this.#stopLoop();
+ }
+ };
+
+ #frame = (now: number) => {
+ const seconds = frameSeconds(now, this.#previous);
+ this.#previous = now;
+ this.#avatar?.advance(seconds, 1 / seconds);
+ this.#raf = requestAnimationFrame(this.#frame);
+ };
+
+ #stopLoop() {
+ cancelAnimationFrame(this.#raf);
+ this.#raf = 0;
+ }
+
+ #warn(name: string, value: string | null) {
+ const key = `${name}=${value}`;
+ if (this.#warned.has(key)) return;
+ this.#warned.add(key);
+ console.warn(`<mesh-avatar> ignores ${name}="${value}".`);
+ }
+}
+
+if (typeof customElements !== 'undefined' && !customElements.get('mesh-avatar')) {
+ customElements.define('mesh-avatar', MeshAvatarElement);
+}
+
+declare global {
+ interface HTMLElementTagNameMap { 'mesh-avatar': MeshAvatarElement }
+}
diff --git a/packages/element/tests/attributes.test.ts b/packages/element/tests/attributes.test.ts
new file mode 100644
index 0000000..7bf7ab8
--- /dev/null
+++ b/packages/element/tests/attributes.test.ts
@@ -0,0 +1,65 @@
+import { describe, expect, it } from 'vitest';
+import { frameSeconds, parseEmotion, parseExpression, parseFit, ReadySignal } from '../src/attributes';
+
+describe('attribute parsing', () => {
+ it('reads expressions, treating a missing attribute as neutral', () => {
+ expect(parseExpression(null)).toBe('neutral');
+ expect(parseExpression('')).toBe('neutral');
+ expect(parseExpression('smile')).toBe('smile');
+ expect(parseExpression('halfLidded')).toBe('halfLidded');
+ expect(parseExpression('grin')).toBeUndefined();
+ });
+
+ it('reads emotions, treating a missing attribute as none', () => {
+ expect(parseEmotion(null)).toBeNull();
+ expect(parseEmotion('happy')).toBe('happy');
+ expect(parseEmotion('Happy')).toBeUndefined();
+ });
+
+ it('reads fit, defaulting to contain', () => {
+ expect(parseFit(null)).toBe('contain');
+ expect(parseFit('cover')).toBe('cover');
+ expect(parseFit('fill')).toBeUndefined();
+ });
+
+ it('limits frame steps like the runtime loop', () => {
+ expect(frameSeconds(1016, 1000)).toBeCloseTo(0.016);
+ expect(frameSeconds(5000, 1000)).toBe(0.05);
+ expect(frameSeconds(1000, 1000)).toBe(0.001);
+ });
+});
+
+describe('ReadySignal', () => {
+ it('keeps one pending promise across loads that start before the previous one finishes', async () => {
+ const ready = new ReadySignal<string>();
+ ready.start();
+ const first = ready.promise;
+ ready.start();
+ expect(ready.promise).toBe(first);
+ ready.resolve('second avatar');
+ await expect(first).resolves.toBe('second avatar');
+ });
+
+ it('starts a new promise after the previous one settled', async () => {
+ const ready = new ReadySignal<string>();
+ ready.start();
+ ready.resolve('first');
+ const first = ready.promise;
+ ready.start();
+ expect(ready.promise).not.toBe(first);
+ ready.reject(new Error('broken file'));
+ await expect(ready.promise).rejects.toThrow('broken file');
+ });
+
+ it('does not report a rejection nobody awaited', async () => {
+ const unhandled: unknown[] = [];
+ const listener = (reason: unknown) => unhandled.push(reason);
+ process.on('unhandledRejection', listener);
+ const ready = new ReadySignal<string>();
+ ready.start();
+ ready.reject(new Error('ignored'));
+ await new Promise(resolve => setTimeout(resolve, 0));
+ process.off('unhandledRejection', listener);
+ expect(unhandled).toEqual([]);
+ });
+});
diff --git a/packages/element/tsconfig.build.json b/packages/element/tsconfig.build.json
new file mode 100644
index 0000000..ba5f39c
--- /dev/null
+++ b/packages/element/tsconfig.build.json
@@ -0,0 +1,16 @@
+{
+ "compilerOptions": {
+ "target": "ES2022",
+ "lib": ["ES2022", "DOM", "DOM.Iterable"],
+ "module": "ESNext",
+ "moduleResolution": "Bundler",
+ "strict": true,
+ "declaration": true,
+ "emitDeclarationOnly": true,
+ "noEmitOnError": true,
+ "rootDir": "src",
+ "outDir": "dist",
+ "types": []
+ },
+ "include": ["src"]
+}
diff --git a/packages/element/vite.config.ts b/packages/element/vite.config.ts
new file mode 100644
index 0000000..29ce122
--- /dev/null
+++ b/packages/element/vite.config.ts
@@ -0,0 +1,22 @@
+import { fileURLToPath } from 'node:url';
+import { defineConfig } from 'vite';
+
+const fromHere = (path: string) => fileURLToPath(new URL(path, import.meta.url));
+
+// `vite build` makes dist/index.js, which imports the mesh-avatar package.
+// `vite build --mode standalone` makes dist/standalone.js with the runtime inside, for a
+// single <script type="module"> from a CDN. The runtime build already carries fflate's
+// license notice, and legal comments are kept.
+export default defineConfig(({ mode }) => {
+ const standalone = mode === 'standalone';
+ return {
+ publicDir: false,
+ esbuild: { legalComments: 'inline' },
+ build: {
+ target: 'es2022',
+ emptyOutDir: !standalone,
+ lib: { entry: fromHere('./src/index.ts'), formats: ['es'], fileName: () => standalone ? 'standalone.js' : 'index.js' },
+ rollupOptions: standalone ? {} : { external: ['mesh-avatar'] },
+ },
+ };
+});
diff --git a/packages/runtime/README.md b/packages/runtime/README.md
index 72a4956..bc7b8d7 100644
--- a/packages/runtime/README.md
+++ b/packages/runtime/README.md
@@ -9,6 +9,8 @@ A WebGL runtime for 2D mesh avatars created with [Mesh Avatar Studio](https://gi
To move an avatar with your own face and voice without installing anything, open the
[Player](https://shinshin86.github.io/mesh-avatar-studio/play/) in Chrome or Edge.
+To embed an avatar with HTML, use [mesh-avatar-element](https://github.com/shinshin86/mesh-avatar-studio/tree/main/packages/element). It provides a `<mesh-avatar>` custom element and a standalone CDN script.
+
## Install
```sh
diff --git a/site/index.html b/site/index.html
index 415f24f..784d692 100644
--- a/site/index.html
+++ b/site/index.html
@@ -199,6 +199,20 @@
</div>
<p class="section-note">Both views use the local development server. Keep the Live page open in its own window while streaming. Without any setup, the <a href="./play/">Player</a> moves a .mavatar file with your camera and microphone in the browser, for OBS Window Capture. <a href="https://github.com/shinshin86/mesh-avatar-studio/blob/main/docs/reference.md#live-and-streaming">Streaming guide <span aria-hidden="true">↗</span></a></p>
</section>
+ <section id="embed-html" class="content-section" aria-labelledby="embed-html-title">
+ <div class="section-heading">
+ <p class="eyebrow">Embed</p>
+ <h2 id="embed-html-title">Embed with HTML</h2>
+ <p>Paste these two lines into your page to show Miko. To use your own avatar, set the src attribute to an exported .mavatar file.</p>
+ </div>
+ <div class="code-card">
+ <div class="code-heading"><h3>mesh-avatar-element <span>HTML</span></h3><button type="button" class="copy-button" data-copy="element-code" aria-describedby="element-feedback" disabled>Copy</button></div>
+ <pre tabindex="0" aria-label="Avatar embed HTML"><code id="element-code" data-lang="html">&lt;script type="module" src="https://cdn.jsdelivr.net/npm/mesh-avatar-element@0/dist/standalone.js"&gt;&lt;/script&gt;
+&lt;mesh-avatar&gt;&lt;/mesh-avatar&gt;</code></pre>
+ <p id="element-feedback" class="copy-feedback" role="status"></p>
+ </div>
+ <p class="section-note"><a href="https://github.com/shinshin86/mesh-avatar-studio/tree/main/packages/element">Sizing, lip sync and more <span aria-hidden="true">↗</span></a></p>
+ </section>
<section id="embed" class="content-section" aria-labelledby="embed-title">
<div class="section-heading">
<p class="eyebrow">Embed with mesh-avatar</p>
diff --git a/site/ja/index.html b/site/ja/index.html
index 563d6eb..67333d9 100644
--- a/site/ja/index.html
+++ b/site/ja/index.html
@@ -199,6 +199,20 @@
</div>
<p class="section-note">どちらの画面もローカルの開発サーバーで動きます。配信中は、操作画面を専用のウィンドウで開いたままにしてください。セットアップなしで試すなら、<a href="./play/">Player</a> で .mavatar ファイルをブラウザ上でカメラとマイクで動かし、OBS のウィンドウキャプチャで取り込めます。<a href="https://github.com/shinshin86/mesh-avatar-studio/blob/main/docs/reference.md#live-and-streaming">配信の詳しい使い方(英語)<span aria-hidden="true">↗</span></a></p>
</section>
+ <section id="embed-html" class="content-section" aria-labelledby="embed-html-title">
+ <div class="section-heading">
+ <p class="eyebrow">埋め込む</p>
+ <h2 id="embed-html-title">HTML を貼って埋め込む</h2>
+ <p>次の2行をページに貼ると、Miko が表示されます。自分のアバターを使う場合は、書き出した .mavatar ファイルを src 属性に指定してください。</p>
+ </div>
+ <div class="code-card">
+ <div class="code-heading"><h3>mesh-avatar-element <span>HTML</span></h3><button type="button" class="copy-button" data-copy="element-code" aria-describedby="element-feedback" disabled>コピー</button></div>
+ <pre tabindex="0" aria-label="埋め込み用の HTML"><code id="element-code" data-lang="html">&lt;script type="module" src="https://cdn.jsdelivr.net/npm/mesh-avatar-element@0/dist/standalone.js"&gt;&lt;/script&gt;
+&lt;mesh-avatar&gt;&lt;/mesh-avatar&gt;</code></pre>
+ <p id="element-feedback" class="copy-feedback" role="status"></p>
+ </div>
+ <p class="section-note"><a href="https://github.com/shinshin86/mesh-avatar-studio/tree/main/packages/element">サイズの指定・口パクの使い方(英語) <span aria-hidden="true">↗</span></a></p>
+ </section>
<section id="embed" class="content-section" aria-labelledby="embed-title">
<div class="section-heading">
<p class="eyebrow">mesh-avatar で組み込む</p>
diff --git a/site/vite.config.ts b/site/vite.config.ts
index 2d20f38..3b255f7 100644
--- a/site/vite.config.ts
+++ b/site/vite.config.ts
@@ -10,6 +10,7 @@ import { mediapipeAssets } from '../src/server/mediapipe-assets';
const fromHere = (path: string) => fileURLToPath(new URL(path, import.meta.url));
const base = '/mesh-avatar-studio/';
+// External mesh-avatar-element embeds use this path as their default src; keep it stable.
const avatarFile = 'miko.mavatar';
const publishedUrl = `https://shinshin86.github.io${base}`;
diff --git a/tsconfig.json b/tsconfig.json
index d1cbd2b..d5b7741 100644
--- a/tsconfig.json
+++ b/tsconfig.json
@@ -25,6 +25,8 @@
"src",
"packages/runtime/src",
"packages/runtime/tests",
+ "packages/element/src",
+ "packages/element/tests",
"tests",
"e2e",
"vite.config.ts",
diff --git a/vite.config.ts b/vite.config.ts
index eb1eca0..8a37396 100644
--- a/vite.config.ts
+++ b/vite.config.ts
@@ -22,5 +22,5 @@ export default defineConfig({
}],
publicDir: 'samples',
build: { rollupOptions: { input: { editor: 'index.html', stream: 'stream.html', live: 'live.html' } } },
- test: { include: ['tests/**/*.test.ts', 'packages/runtime/tests/**/*.test.ts'] },
+ test: { include: ['tests/**/*.test.ts', 'packages/runtime/tests/**/*.test.ts', 'packages/element/tests/**/*.test.ts'] },
});