Skip to content

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

Add examples, a live demo page and load() for files

shinshin866c6d29859082
diff --git a/.github/workflows/pages.yml b/.github/workflows/pages.yml
index 1dcb14b..a097a16 100644
--- a/.github/workflows/pages.yml
+++ b/.github/workflows/pages.yml
@@ -7,6 +7,7 @@ on:
- 'site/**'
- 'docs/images/**'
- 'packages/runtime/src/**'
+ - 'packages/element/**'
- 'samples/miko-qipao/**'
# The Player page reuses Studio's Live, lighting and tracking files.
- 'src/live/**'
diff --git a/e2e/embed-demo.spec.ts b/e2e/embed-demo.spec.ts
new file mode 100644
index 0000000..bd830f8
--- /dev/null
+++ b/e2e/embed-demo.spec.ts
@@ -0,0 +1,184 @@
+import { expect, test, type Page } from '@playwright/test';
+import { PNG } from 'pngjs';
+import { readFile } from 'node:fs/promises';
+import { samplePresent, sampleSkipReason } from './sample';
+
+const site = `http://127.0.0.1:${process.env.PLAYWRIGHT_SITE_PORT ?? 5174}/mesh-avatar-studio/`;
+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 => {
+ if (new URL(route.request().url()).hostname !== '127.0.0.1') {
+ requests.push(route.request().url());
+ return route.abort();
+ }
+ return route.continue();
+ });
+});
+test.afterEach(({ page }) => { expect(outside.get(page) ?? []).toEqual([]); });
+
+for (const language of ['en', 'ja']) {
+ test(`embed demo works in ${language} without outside requests`, async ({ page }) => {
+ const errors: string[] = [];
+ page.on('pageerror', error => errors.push(error.message));
+ await page.goto(`${site}${language === 'ja' ? 'ja/' : ''}embed/`);
+ await expect(page.locator('#status')).toHaveAttribute('data-state', 'ready');
+ await expect(page.locator('html')).toHaveAttribute('lang', language);
+ const image = PNG.sync.read(await page.locator('mesh-avatar canvas').screenshot({ omitBackground: true }));
+ expect(image.data.some((value, index) => index % 4 === 3 && value > 0)).toBe(true);
+ await page.locator('[data-expression="smile"]').click();
+ expect(await page.evaluate(() => document.querySelector('mesh-avatar')!.avatar!.getExpression().name)).toBe('smile');
+ await page.locator('#emotion').selectOption('happy');
+ await page.locator('#emotion').selectOption('');
+ await page.locator('#paused').check();
+ expect(await page.evaluate(() => document.querySelector('mesh-avatar')!.paused)).toBe(true);
+ await page.locator('#paused').uncheck();
+ await page.locator('#no-idle').check();
+ await expect(page.locator('mesh-avatar')).toHaveAttribute('no-idle', '');
+ await page.locator('#speech-text').fill('こんにちは、よろしくお願いします。');
+ await page.locator('#speech-form button').click();
+ expect(await page.evaluate(() => document.querySelector('mesh-avatar')!.avatar!.getLipSyncState().active)).toBe(true);
+
+ await page.evaluate(() => Reflect.set(window, 'previousAvatar', document.querySelector('mesh-avatar')!.avatar));
+ const archive = await (await page.request.get(`${site}miko.mavatar`)).body();
+ await page.locator('#avatar-file').setInputFiles({
+ name: 'chosen.mavatar', mimeType: 'application/octet-stream', buffer: archive,
+ });
+ await expect(page.locator('#status')).toHaveAttribute('data-state', 'ready');
+ await expect(page.locator('#source-name')).toHaveText('chosen.mavatar');
+ expect(await page.evaluate(() => document.querySelector('mesh-avatar')!.avatar !== Reflect.get(window, 'previousAvatar'))).toBe(true);
+ await page.locator('#restore-miko').click();
+ await expect(page.locator('#source-name')).toHaveText('Miko');
+ await expect(page.locator('#status')).toHaveAttribute('data-state', 'ready');
+
+ await page.locator('#avatar-file').setInputFiles({
+ name: 'broken.mavatar', mimeType: 'application/octet-stream', buffer: Buffer.from('broken'),
+ });
+ await expect(page.locator('#status')).toHaveAttribute('data-state', 'error');
+ await page.locator('#restore-miko').click();
+ await expect(page.locator('#status')).toHaveAttribute('data-state', 'ready');
+ await expect(page.locator('.language-switch')).toHaveAttribute('href', language === 'ja' ? '../../embed/' : '../ja/embed/');
+ expect(errors).toEqual([]);
+ });
+}
+
+test('microphone input drives the mouth and stopping releases the stream', async ({ page }) => {
+ await page.addInitScript(() => {
+ Object.defineProperty(navigator.mediaDevices, 'getUserMedia', { value: async () => {
+ const ctx = new AudioContext();
+ await ctx.resume();
+ const oscillator = ctx.createOscillator();
+ const destination = ctx.createMediaStreamDestination();
+ oscillator.connect(destination);
+ oscillator.start();
+ const stream = destination.stream;
+ const track = stream.getAudioTracks()[0], stop = track.stop.bind(track);
+ track.stop = () => {
+ Reflect.set(window, 'microphoneStopped', true);
+ oscillator.stop();
+ void ctx.close();
+ stop();
+ };
+ return stream;
+ } });
+ });
+ await page.goto(`${site}embed/`);
+ await expect(page.locator('#status')).toHaveAttribute('data-state', 'ready');
+ await page.evaluate(() => {
+ const el = document.querySelector('mesh-avatar')!;
+ const set = el.setVoiceLevel.bind(el);
+ el.setVoiceLevel = value => {
+ Reflect.set(window, 'voiceLevel', value);
+ set(value);
+ };
+ });
+ await page.locator('#microphone').click();
+ await expect(page.locator('#microphone')).toHaveAttribute('aria-pressed', 'true');
+ await expect.poll(() => page.evaluate(() => Number(Reflect.get(window, 'voiceLevel')))).toBeGreaterThan(0.1);
+ await page.locator('#microphone').click();
+ await expect(page.locator('#microphone')).toHaveAttribute('aria-pressed', 'false');
+ expect(await page.evaluate(() => Reflect.get(window, 'microphoneStopped'))).toBe(true);
+ expect(await page.evaluate(() => Reflect.get(window, 'voiceLevel'))).toBe(0);
+});
+
+test('microphone denial leaves controls usable and shows a localized message', async ({ page }) => {
+ await page.addInitScript(() => {
+ Object.defineProperty(navigator.mediaDevices, 'getUserMedia', {
+ value: async () => { throw new DOMException('Denied', 'NotAllowedError'); },
+ });
+ });
+ await page.goto(`${site}ja/embed/`);
+ await expect(page.locator('#status')).toHaveAttribute('data-state', 'ready');
+ await page.locator('#microphone').click();
+ await expect(page.locator('#notice')).toContainText('マイクを開始できませんでした');
+ await expect(page.locator('#microphone')).toBeEnabled();
+ await expect(page.locator('#microphone')).toHaveAttribute('aria-pressed', 'false');
+});
+
+test('local audio drives mouth volume and resets it when playback stops', async ({ page }) => {
+ const sampleRate = 16000, samples = sampleRate * 2;
+ const wav = Buffer.alloc(44 + samples * 2);
+ wav.write('RIFF', 0);
+ wav.writeUInt32LE(wav.length - 8, 4);
+ wav.write('WAVEfmt ', 8);
+ wav.writeUInt32LE(16, 16);
+ wav.writeUInt16LE(1, 20);
+ wav.writeUInt16LE(1, 22);
+ wav.writeUInt32LE(sampleRate, 24);
+ wav.writeUInt32LE(sampleRate * 2, 28);
+ wav.writeUInt16LE(2, 32);
+ wav.writeUInt16LE(16, 34);
+ wav.write('data', 36);
+ wav.writeUInt32LE(samples * 2, 40);
+ for (let i = 0; i < samples; i++) wav.writeInt16LE(Math.round(Math.sin(i * 440 * 2 * Math.PI / sampleRate) * 10000), 44 + i * 2);
+ await page.goto(`${site}embed/`);
+ await expect(page.locator('#status')).toHaveAttribute('data-state', 'ready');
+ await page.evaluate(() => {
+ const el = document.querySelector('mesh-avatar')!;
+ const set = el.setVoiceLevel.bind(el);
+ el.setVoiceLevel = value => {
+ Reflect.set(window, 'voiceLevel', value);
+ set(value);
+ };
+ });
+ await page.locator('#audio-file').setInputFiles({ name: 'voice.wav', mimeType: 'audio/wav', buffer: wav });
+ // Give the Web Audio context a user gesture before programmatic playback.
+ await page.locator('#speech-form button').click();
+ await page.locator('audio').evaluate(async audio => { await (audio as HTMLAudioElement).play(); });
+ await expect.poll(() => page.evaluate(() => Number(Reflect.get(window, 'voiceLevel')))).toBeGreaterThan(0.1);
+ await page.locator('audio').evaluate(audio => (audio as HTMLAudioElement).pause());
+ await expect.poll(() => page.evaluate(() => Reflect.get(window, 'voiceLevel'))).toBe(0);
+ await expect(page.locator('#notice')).toHaveText('');
+});
+
+for (const example of ['basic', 'playground']) {
+ test(`standalone ${example} example opens directly from disk`, async ({ page }) => {
+ // Use the unpublished build at the real CDN URL, without sending any requests outside.
+ const bundle = await readFile(new URL('../packages/element/dist/standalone.js', import.meta.url));
+ const archive = await (await page.request.get(`${site}miko.mavatar`)).body();
+ await page.route('https://cdn.jsdelivr.net/npm/mesh-avatar-element@0/dist/standalone.js', route => route.fulfill({
+ contentType: 'text/javascript', headers: { 'access-control-allow-origin': '*' }, body: bundle,
+ }));
+ await page.route('https://shinshin86.github.io/mesh-avatar-studio/miko.mavatar', route => route.fulfill({
+ contentType: 'application/octet-stream', headers: { 'access-control-allow-origin': '*' }, body: archive,
+ }));
+ // Local file navigation is the feature under test, so it bypasses the HTTP-only guard.
+ await page.route('file://**', route => route.continue());
+ await page.goto(new URL(`../packages/element/examples/${example}.html`, import.meta.url).href);
+ await expect.poll(() => page.evaluate(() => !!document.querySelector('mesh-avatar')?.avatar)).toBe(true);
+ if (example === 'playground') {
+ await expect(page.locator('#status')).toHaveAttribute('data-state', 'ready');
+ await page.locator('[data-expression="wink"]').click();
+ expect(await page.evaluate(() => document.querySelector('mesh-avatar')!.avatar!.getExpression().name)).toBe('wink');
+ await page.locator('#avatar-file').setInputFiles({ name: 'chosen.mavatar', mimeType: 'application/octet-stream', buffer: archive });
+ await expect(page.locator('#source-name')).toHaveText('chosen.mavatar');
+ await expect(page.locator('#status')).toHaveAttribute('data-state', 'ready');
+ await page.locator('#restore-miko').click();
+ await expect(page.locator('#source-name')).toHaveText('Miko');
+ await expect(page.locator('#status')).toHaveAttribute('data-state', 'ready');
+ }
+ });
+}
diff --git a/e2e/embed-element.spec.ts b/e2e/embed-element.spec.ts
index c81df6e..bd4b0bf 100644
--- a/e2e/embed-element.spec.ts
+++ b/e2e/embed-element.spec.ts
@@ -163,3 +163,52 @@ test('unknown expression warns once without throwing or changing the expression'
expect(errors).toEqual([]);
expect(await page.evaluate(() => document.querySelector('mesh-avatar')!.avatar!.getExpression().name)).toBe('smile');
});
+
+test('load accepts a File, retains it for fit and reconnection, and src restores URL loading', async ({ page }) => {
+ await open(page);
+ const before = await page.evaluate(() => Reflect.get(window, 'loads'));
+ expect(await page.evaluate(async url => {
+ const el = document.querySelector('mesh-avatar')!;
+ const old = el.avatar;
+ const blob = await (await fetch(url)).blob();
+ const pending = el.load(new File([blob], 'chosen.mavatar'));
+ return pending === el.ready && await pending !== old && el.getAttribute('src') === null;
+ }, sample)).toBe(true);
+ await drawn(page);
+ // If fit or reconnection forgets the File, a fallback URL load will now fail.
+ await page.route(defaultSrc, route => route.abort());
+ await page.locator('mesh-avatar').evaluate(async el => {
+ const avatar = el as MeshAvatarElement;
+ avatar.fit = 'cover';
+ await avatar.ready;
+ avatar.remove();
+ await Promise.resolve();
+ document.querySelector('#first')!.appendChild(avatar);
+ await avatar.ready;
+ });
+ await expect.poll(() => page.evaluate(() => Reflect.get(window, 'loads'))).toBe(before + 3);
+ expect(await page.evaluate(async url => {
+ const el = document.querySelector('mesh-avatar')!;
+ const old = el.avatar;
+ el.src = url;
+ return await el.ready !== old && el.src === url;
+ }, sample + '?after-file')).toBe(true);
+ await drawn(page);
+});
+
+test('load rejects broken archive data, emits error and recovers from a subsequent load', async ({ page }) => {
+ const errors: string[] = [];
+ page.on('pageerror', error => errors.push(error.message));
+ await open(page);
+ expect(await page.evaluate(async url => {
+ const el = document.querySelector('mesh-avatar')!;
+ let rejected = false;
+ try { await el.load(new Blob(['broken'])); } catch { rejected = true; }
+ const empty = el.avatar === null;
+ await el.load(new URL(url));
+ return rejected && empty && !!el.avatar;
+ }, sample)).toBe(true);
+ expect(await page.evaluate(() => Reflect.get(window, 'errors'))).toBe(1);
+ expect(errors).toEqual([]);
+ await drawn(page);
+});
diff --git a/packages/element/README.md b/packages/element/README.md
index 8791820..4111d5c 100644
--- a/packages/element/README.md
+++ b/packages/element/README.md
@@ -64,7 +64,7 @@ The element defaults to `display: block; aspect-ratio: 3 / 4`. Set its width in
| `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.
+Attributes can be changed after loading. Changing `src` or `fit` destroys the current avatar and loads a new one. After `load(source)`, changing `fit` reloads that source; changing `src` switches back to the attribute URL. 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
@@ -80,7 +80,8 @@ 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. |
+| `load(source)` | Loads a File, Blob, ArrayBuffer, Uint8Array, URL or URL string without changing `src`. Returns the loading promise and emits `load` or `error`. The `AvatarSource` type is re-exported from `mesh-avatar`. |
+| `ready` | Promise resolving with the avatar for the current source, 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`. |
@@ -95,7 +96,35 @@ el.avatar.setExpression('smile');
| `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.
+Moving the element between parents in the same turn preserves the avatar. Removing it destroys the avatar; reconnecting it reloads the last source, including a File passed to `load()`.
+
+To display a `.mavatar` chosen with a file input, pass the File directly rather than a `blob:` URL:
+
+```html
+<input id="avatar-file" type="file" accept=".mavatar">
+<mesh-avatar></mesh-avatar>
+<script type="module">
+await customElements.whenDefined('mesh-avatar');
+const el = document.querySelector('mesh-avatar');
+document.querySelector('#avatar-file').onchange = async event => {
+ const file = event.target.files[0];
+ if (!file) return;
+ try {
+ await el.load(file);
+ } catch (error) {
+ console.error('Could not load avatar:', error);
+ }
+};
+</script>
+```
+
+## Examples
+
+- [Basic embed](https://github.com/shinshin86/mesh-avatar-studio/blob/main/packages/element/examples/basic.html): two HTML lines and a CSS width.
+- [Playground](https://github.com/shinshin86/mesh-avatar-studio/blob/main/packages/element/examples/playground.html): expressions, text and audio lip sync, microphone input and your own avatar files.
+- [Interactive demo](https://shinshin86.github.io/mesh-avatar-studio/embed/) ([日本語](https://shinshin86.github.io/mesh-avatar-studio/ja/embed/)): try the controls in your browser.
+
+Download either HTML example and open it directly, or serve it on your site. Both load the element and Miko over the internet. Microphone access depends on browser permissions and secure-context support; use HTTPS or localhost if it is unavailable when opening a file directly. Examples are in the repository and are not included in the npm package.
## Lip sync
diff --git a/packages/element/examples/basic.html b/packages/element/examples/basic.html
new file mode 100644
index 0000000..e649195
--- /dev/null
+++ b/packages/element/examples/basic.html
@@ -0,0 +1,13 @@
+<!doctype html>
+<html lang="en">
+<head>
+ <meta charset="UTF-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1">
+ <title>Mesh Avatar basic embed</title>
+ <style>mesh-avatar { width: min(100%, 320px); }</style>
+</head>
+<body>
+ <script type="module" src="https://cdn.jsdelivr.net/npm/mesh-avatar-element@0/dist/standalone.js"></script>
+ <mesh-avatar></mesh-avatar>
+</body>
+</html>
diff --git a/packages/element/examples/playground.html b/packages/element/examples/playground.html
new file mode 100644
index 0000000..81e65dc
--- /dev/null
+++ b/packages/element/examples/playground.html
@@ -0,0 +1,338 @@
+<!doctype html>
+<html lang="en">
+<head>
+ <meta charset="UTF-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1">
+ <title>Mesh Avatar playground</title>
+ <style>
+html { font-family: system-ui, sans-serif; color: #243348; background: #edf1f5; }
+* { box-sizing: border-box; }
+body { margin: 0; }
+:root { --ink: #243348; --muted: #64758a; --line: #d7dfe8; --surface: white; --accent: #2563eb; --accent-soft: #edf3ff; }
+button, input, select { font: inherit; }
+button:focus-visible, a:focus-visible { outline: 3px solid #2563eb; outline-offset: 3px; }
+.shell { width: min(960px, calc(100% - 32px)); margin: auto; }
+.sr-only { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); }
+fieldset { min-width: 0; margin: 0; padding: 0; border: 0; }
+.expression-chips { display: flex; flex-wrap: wrap; gap: 6px; }
+a { color: #2563eb; }
+footer { padding-block: 24px; font-size: 13px; line-height: 1.7; }
+.embed-page { padding-bottom: 40px; }
+.embed-page .site-header { min-height: 76px; }
+.embed-page .intro { padding-block: 36px 24px; }
+.embed-page h1 { font-size: clamp(30px, 4vw, 44px); letter-spacing: -1px; line-height: 1.25; }
+.embed-page .intro > p { max-width: 780px; color: var(--muted); line-height: 1.7; }
+.embed-page .code-card { margin-block: 16px; }
+.embed-page .code-card pre { padding-block: 12px; }
+.embed-layout { display: grid; grid-template-columns: minmax(240px, .8fr) minmax(0, 1.2fr); gap: 24px; align-items: start; margin-top: 28px; }
+.embed-stage, .control-panel { min-width: 0; padding: 20px; border: 1px solid var(--line); border-radius: 12px; background: var(--surface); }
+.embed-stage { position: sticky; top: 20px; text-align: center; }
+.embed-stage mesh-avatar { width: min(100%, 340px); margin: auto; background: #f7f9fc; border-radius: 8px; }
+.embed-stage #status { margin-bottom: 0; font-size: 14px; color: var(--muted); }
+.embed-stage #status[data-state='error'], #notice { color: #a52b2b; }
+.embed-stage #source-name { margin: 12px 0 0; font-size: 13px; overflow-wrap: anywhere; }
+.embed-panels { display: grid; gap: 16px; min-width: 0; }
+.control-panel h2, .control-panel legend { margin: 0 0 16px; font-size: 18px; font-weight: 650; letter-spacing: 0; }
+.control-panel label { display: block; margin-block: 12px 8px; font-size: 14px; }
+.control-panel .check { display: flex; align-items: center; gap: 8px; }
+.control-panel input[type='file'] { display: block; width: 100%; font-size: 13px; margin-bottom: 12px; }
+.control-panel input[type='text'], .control-panel select { width: 100%; min-height: 40px; padding: 8px 10px; border: 1px solid var(--line); border-radius: 6px; font: inherit; background: white; color: var(--ink); }
+.control-panel button { min-height: 40px; padding: 8px 12px; border: 1px solid var(--line); border-radius: 8px; background: white; color: var(--ink); cursor: pointer; }
+.control-panel button:hover:not(:disabled), .control-panel button[aria-pressed='true'] { border-color: var(--accent); color: var(--accent); background: var(--accent-soft); }
+.control-panel button:disabled { opacity: .5; cursor: default; }
+.control-panel audio { display: block; width: 100%; margin-block: 12px; }
+.control-panel form button { margin-top: 12px; }
+.control-panel .expression-chips { margin-bottom: 16px; }
+.control-panel .expression-chips button { flex: 0 0 auto; white-space: nowrap; }
+.control-panel .hint, .embed-privacy { color: var(--muted); font-size: 13px; line-height: 1.7; }
+#avatar-controls { display: grid; gap: 16px; }
+#notice { margin: 0; font-size: 14px; line-height: 1.6; }
+.embed-page input:focus-visible, .embed-page select:focus-visible { outline: 3px solid var(--accent); outline-offset: 3px; }
+@media (max-width: 760px) {
+ .embed-page .shell { width: calc(100% - 32px); }
+ .embed-page .site-header { flex-wrap: wrap; padding-block: 16px; }
+ .embed-page .primary-nav { gap: 16px; }
+ .embed-layout { grid-template-columns: 1fr; }
+ .embed-stage { position: static; }
+ .embed-stage mesh-avatar { width: min(100%, 270px); }
+}
+ </style>
+</head>
+<body class="embed-page">
+ <main id="embed-playground" class="shell" data-loading="Loading avatar…" data-ready="Avatar ready" data-error="Could not load this avatar. Choose another file or return to Miko." data-audio-error="Could not play this audio file." data-mic-error="Could not start the microphone. Check browser permissions and use HTTPS or localhost." data-copy-error="Select and copy the code above.">
+ <section class="intro">
+ <h1>Mesh Avatar playground</h1>
+ <p>Try expressions, lip sync and your own .mavatar files.</p>
+ </section>
+ <div class="embed-layout">
+ <section class="embed-stage" aria-label="Avatar preview">
+ <mesh-avatar label="Miko"></mesh-avatar>
+ <p id="source-name">Miko</p>
+ <p id="status" role="status" data-state="loading">Loading avatar…</p>
+ </section>
+ <div class="embed-panels">
+ <section class="control-panel">
+ <h2>Avatar file</h2>
+ <label for="avatar-file">Choose a .mavatar file</label>
+ <input id="avatar-file" type="file" accept=".mavatar">
+ <button id="restore-miko" type="button">Return to Miko</button>
+ </section>
+ <fieldset id="avatar-controls" disabled>
+ <legend class="sr-only">Avatar controls</legend>
+ <section class="control-panel">
+ <h2>Expressions</h2>
+ <div class="expression-chips" role="group" aria-label="Expressions">
+ <button type="button" data-expression="neutral" aria-pressed="true">Neutral</button>
+ <button type="button" data-expression="smile" aria-pressed="false">Smile</button>
+ <button type="button" data-expression="shy" aria-pressed="false">Shy</button>
+ <button type="button" data-expression="surprise" aria-pressed="false">Surprise</button>
+ <button type="button" data-expression="halfLidded" aria-pressed="false">Half-lidded</button>
+ <button type="button" data-expression="angry" aria-pressed="false">Angry</button>
+ <button type="button" data-expression="sad" aria-pressed="false">Sad</button>
+ <button type="button" data-expression="wink" aria-pressed="false">Wink</button>
+ </div>
+ <label for="emotion">Emotion</label>
+ <select id="emotion"><option value="">None</option><option value="happy">Happy</option><option value="sad">Sad</option><option value="angry">Angry</option><option value="surprised">Surprised</option><option value="relaxed">Relaxed</option><option value="neutral">Neutral</option></select>
+ <label class="check"><input id="paused" type="checkbox">Pause animation</label>
+ <label class="check"><input id="no-idle" type="checkbox">Disable idle motion</label>
+ </section>
+ <section class="control-panel">
+ <h2>Text lip sync</h2>
+ <form id="speech-form">
+ <label for="speech-text">Japanese text</label>
+ <input id="speech-text" type="text" value="こんにちは" maxlength="300">
+ <button type="submit">Animate speech</button>
+ </form>
+ <p class="hint">Mouth animation only. No voice is generated.</p>
+ </section>
+ <section class="control-panel">
+ <h2>Audio lip sync</h2>
+ <label for="audio-file">Choose an audio file</label>
+ <input id="audio-file" type="file" accept="audio/*">
+ <audio controls aria-label="Audio lip sync"></audio>
+ <button id="microphone" type="button" aria-pressed="false" data-start="Start microphone" data-stop="Stop microphone">Start microphone</button>
+ </section>
+ </fieldset>
+ <p id="notice" role="status"></p>
+ <p class="embed-privacy">Avatar files, audio files and microphone audio are processed in your browser and are not uploaded.</p>
+ </div>
+ </div>
+ </main>
+ <footer class="shell"><p>Miko © Yuki Shindo (AITuber OnAir). <a href="https://miko.aituberonair.com/#terms">Miko character guidelines</a></p></footer>
+ <script type="module">
+import 'https://cdn.jsdelivr.net/npm/mesh-avatar-element@0/dist/standalone.js';
+
+// Kept inline in the standalone example so it can also open directly from disk.
+function setupPlayground(root, { sampleURL }) {
+ const el = root.querySelector('mesh-avatar');
+ const status = root.querySelector('#status');
+ const sourceName = root.querySelector('#source-name');
+ const controls = root.querySelector('#avatar-controls');
+ const audio = root.querySelector('audio');
+ const micButton = root.querySelector('#microphone');
+ const notice = root.querySelector('#notice');
+ let context;
+ let audioAnalyser;
+ let audioURL;
+ let microphone;
+ let microphoneSource;
+ let microphoneRequest = 0;
+ let voiceFrame = 0;
+
+ function stopVoice() {
+ cancelAnimationFrame(voiceFrame);
+ voiceFrame = 0;
+ el.avatar?.setSpeaking(false);
+ el.setVoiceLevel(0);
+ }
+
+ function stopMicrophone() {
+ microphoneRequest++;
+ microphone?.getTracks().forEach(track => track.stop());
+ microphone = undefined;
+ microphoneSource?.disconnect();
+ microphoneSource = undefined;
+ micButton.disabled = false;
+ micButton.textContent = micButton.dataset.start;
+ micButton.setAttribute('aria-pressed', 'false');
+ stopVoice();
+ }
+
+ function followVolume(analyser) {
+ stopVoice();
+ el.avatar?.stopLipSync();
+ el.avatar?.setSpeaking(true);
+ const data = new Float32Array(analyser.fftSize);
+ const frame = () => {
+ analyser.getFloatTimeDomainData(data);
+ const rms = Math.sqrt(data.reduce((sum, value) => sum + value * value, 0) / data.length);
+ el.setVoiceLevel(Math.min(1, rms * 5));
+ voiceFrame = requestAnimationFrame(frame);
+ };
+ frame();
+ }
+
+ function audioContext() {
+ context ??= new AudioContext();
+ return context;
+ }
+
+ function loading(name) {
+ audio.pause();
+ stopMicrophone();
+ sourceName.textContent = name;
+ status.textContent = root.dataset.loading;
+ status.dataset.state = 'loading';
+ controls.disabled = true;
+ notice.textContent = '';
+ }
+
+ function ready() {
+ status.textContent = root.dataset.ready;
+ status.dataset.state = 'ready';
+ controls.disabled = false;
+ }
+
+ el.addEventListener('load', ready);
+ el.addEventListener('error', () => {
+ status.textContent = root.dataset.error;
+ status.dataset.state = 'error';
+ controls.disabled = true;
+ });
+ // Also cover callers that initialize controls after the avatar has loaded.
+ if (el.avatar) ready();
+
+ for (const button of root.querySelectorAll('[data-expression]')) {
+ button.addEventListener('click', () => {
+ el.expression = button.dataset.expression;
+ for (const chip of root.querySelectorAll('[data-expression]')) {
+ chip.setAttribute('aria-pressed', String(chip === button));
+ }
+ });
+ }
+ root.querySelector('#emotion').addEventListener('change', event => {
+ el.emotion = event.target.value || null;
+ });
+ root.querySelector('#paused').addEventListener('change', event => {
+ el.paused = event.target.checked;
+ });
+ root.querySelector('#no-idle').addEventListener('change', event => {
+ el.toggleAttribute('no-idle', event.target.checked);
+ });
+
+ root.querySelector('#speech-form').addEventListener('submit', event => {
+ event.preventDefault();
+ audio.pause();
+ stopMicrophone();
+ void el.speak(root.querySelector('#speech-text').value).catch(() => {
+ notice.textContent = root.dataset.error;
+ });
+ });
+
+ root.querySelector('#avatar-file').addEventListener('change', event => {
+ const file = event.target.files?.[0];
+ if (!file) return;
+ loading(file.name);
+ void el.load(file).catch(() => {});
+ event.target.value = '';
+ });
+ root.querySelector('#restore-miko').addEventListener('click', () => {
+ loading('Miko');
+ // Setting an unchanged src or removing an absent attribute would not reload.
+ void el.load(sampleURL).catch(() => {});
+ root.querySelector('#avatar-file').value = '';
+ });
+
+ root.querySelector('#audio-file').addEventListener('change', event => {
+ const file = event.target.files?.[0];
+ if (!file) return;
+ audio.pause();
+ stopMicrophone();
+ if (audioURL) URL.revokeObjectURL(audioURL);
+ audioURL = URL.createObjectURL(file);
+ audio.src = audioURL;
+ notice.textContent = '';
+ });
+ audio.addEventListener('play', async () => {
+ stopMicrophone();
+ try {
+ const ctx = audioContext();
+ audioAnalyser ??= ctx.createAnalyser();
+ if (!audio.dataset.connected) {
+ ctx.createMediaElementSource(audio).connect(audioAnalyser);
+ audioAnalyser.connect(ctx.destination);
+ audio.dataset.connected = 'true';
+ }
+ await ctx.resume();
+ if (!audio.paused && !audio.ended) followVolume(audioAnalyser);
+ } catch {
+ audio.pause();
+ notice.textContent = root.dataset.audioError;
+ }
+ });
+ for (const event of ['pause', 'ended']) audio.addEventListener(event, () => {
+ if (!microphone) stopVoice();
+ });
+ audio.addEventListener('error', () => {
+ if (audio.getAttribute('src')) notice.textContent = root.dataset.audioError;
+ if (!microphone) stopVoice();
+ });
+
+ micButton.addEventListener('click', async () => {
+ if (microphone) {
+ stopMicrophone();
+ return;
+ }
+ audio.pause();
+ stopVoice();
+ notice.textContent = '';
+ const request = ++microphoneRequest;
+ micButton.disabled = true;
+ try {
+ const ctx = audioContext();
+ await ctx.resume();
+ const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
+ if (request !== microphoneRequest) {
+ stream.getTracks().forEach(track => track.stop());
+ return;
+ }
+ microphone = stream;
+ const analyser = ctx.createAnalyser();
+ microphoneSource = ctx.createMediaStreamSource(stream);
+ microphoneSource.connect(analyser);
+ followVolume(analyser);
+ micButton.textContent = micButton.dataset.stop;
+ micButton.setAttribute('aria-pressed', 'true');
+ } catch {
+ if (request === microphoneRequest) {
+ stopMicrophone();
+ notice.textContent = root.dataset.micError;
+ }
+ } finally {
+ if (request === microphoneRequest) micButton.disabled = false;
+ }
+ });
+
+ root.querySelector('#copy-snippet')?.addEventListener('click', async event => {
+ try {
+ await navigator.clipboard.writeText(root.querySelector('#embed-code').textContent);
+ event.target.textContent = event.target.dataset.copied;
+ } catch {
+ notice.textContent = root.dataset.copyError;
+ }
+ });
+
+ window.addEventListener('pagehide', () => {
+ audio.pause();
+ stopMicrophone();
+ if (audioURL) URL.revokeObjectURL(audioURL);
+ if (context) void context.close();
+ }, { once: true });
+}
+
+setupPlayground(document.querySelector('#embed-playground'), {
+ sampleURL: 'https://shinshin86.github.io/mesh-avatar-studio/miko.mavatar',
+});
+ </script>
+</body>
+</html>
diff --git a/packages/element/package.json b/packages/element/package.json
index b6e2446..f9dc2db 100644
--- a/packages/element/package.json
+++ b/packages/element/package.json
@@ -20,6 +20,7 @@
"mesh-avatar"
],
"sideEffects": [
+ "./src/index.ts",
"./dist/index.js",
"./dist/standalone.js"
],
diff --git a/packages/element/src/index.ts b/packages/element/src/index.ts
index b7989d5..09812a8 100644
--- a/packages/element/src/index.ts
+++ b/packages/element/src/index.ts
@@ -1,9 +1,9 @@
-import { loadMeshAvatar, type MeshAvatar } from 'mesh-avatar';
+import { loadMeshAvatar, type AvatarSource, 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';
+export type { AvatarSource, MeshAvatar, LiveExpression } from 'mesh-avatar';
const STYLE = `
:host { display: block; position: relative; aspect-ratio: 3 / 4; }
@@ -26,6 +26,7 @@ export class MeshAvatarElement extends Base {
#ready = new ReadySignal<MeshAvatar>();
#loadId = 0;
#loading = false;
+ #source: AvatarSource | undefined;
#raf = 0;
#previous = 0;
#onScreen = true;
@@ -49,9 +50,16 @@ export class MeshAvatarElement extends Base {
/** 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. */
+ /** Resolves with the avatar once the current source has loaded. */
get ready() { return this.#ready.promise; }
+ /** Loads a file, archive or URL without changing `src`. A changed `src` replaces this source. */
+ load(source: AvatarSource): Promise<MeshAvatar> {
+ this.#source = source;
+ void this.#load();
+ return this.ready;
+ }
+
get src() { return this.getAttribute('src') ?? ''; }
set src(value: string) { this.setAttribute('src', value); }
get fit(): Fit { return parseFit(this.getAttribute('fit')) ?? 'contain'; }
@@ -101,6 +109,7 @@ export class MeshAvatarElement extends Base {
attributeChangedCallback(name: string, old: string | null, value: string | null) {
if (old === value) return;
if (name === 'src' || name === 'fit') {
+ if (name === 'src') this.#source = undefined;
if (name === 'fit' && parseFit(value) === undefined) this.#warn(name, value);
if (this.isConnected) this.#load();
} else if (name === 'label') {
@@ -124,13 +133,13 @@ export class MeshAvatarElement extends Base {
}
}
- async #load() {
+ async #load(source: AvatarSource = this.#source ?? (this.getAttribute('src') || DEFAULT_SRC)) {
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 });
+ const avatar = await loadMeshAvatar(this.#canvas, source, { manual: true, fit: this.fit });
if (id !== this.#loadId) { avatar.destroy(); return; }
this.#loading = false;
this.#avatar = avatar;
diff --git a/site/embed/index.html b/site/embed/index.html
new file mode 100644
index 0000000..493abcf
--- /dev/null
+++ b/site/embed/index.html
@@ -0,0 +1,98 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="UTF-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1">
+ <meta http-equiv="Content-Security-Policy" content="connect-src 'self' blob: data: ws://127.0.0.1:* ws://localhost:*; img-src 'self' blob: data:; media-src 'self' blob:; object-src 'none'; base-uri 'self'">
+ <meta name="description" content="Try expressions, text lip sync and your own avatar files. Without a src attribute, the element loads the same Miko from GitHub Pages.">
+ <title>Mesh Avatar — Try the HTML embed</title>
+ <link rel="canonical" href="https://shinshin86.github.io/mesh-avatar-studio/embed/">
+ <link rel="alternate" hreflang="en" href="https://shinshin86.github.io/mesh-avatar-studio/embed/">
+ <link rel="alternate" hreflang="ja" href="https://shinshin86.github.io/mesh-avatar-studio/ja/embed/">
+ <link rel="alternate" hreflang="x-default" href="https://shinshin86.github.io/mesh-avatar-studio/embed/">
+ <link rel="icon" href="/favicon.svg" type="image/svg+xml">
+ <link rel="apple-touch-icon" href="/apple-touch-icon.png">
+ <script type="module" src="/src/embed/main.ts"></script>
+ </head>
+ <body class="embed-page">
+ <header class="site-header shell">
+ <a class="brand" href="../">Mesh Avatar Studio</a>
+ <nav class="primary-nav" aria-label="Navigation">
+ <a class="header-link" href="../">Home</a>
+ <a class="header-link language-switch" href="../ja/embed/" lang="ja">日本語</a>
+ </nav>
+ </header>
+ <main id="embed-playground" class="shell" data-loading="Loading avatar…" data-ready="Avatar ready" data-error="Could not load this avatar. Choose another file or return to Miko." data-audio-error="Could not play this audio file." data-mic-error="Could not start the microphone. Check browser permissions and use HTTPS or localhost." data-copy-error="Select and copy the code above.">
+ <section class="intro" aria-labelledby="embed-title">
+ <p class="eyebrow">mesh-avatar-element</p>
+ <h1 id="embed-title">Try the HTML embed</h1>
+ <p>Try expressions, text lip sync and your own avatar files. Without a src attribute, the element loads the same Miko from GitHub Pages.</p>
+ <div class="code-card">
+ <div class="code-heading">
+ <h2>Embed on your page <span>HTML</span></h2>
+ <button id="copy-snippet" type="button" class="copy-button" data-copied="Copied">Copy</button>
+ </div>
+ <pre tabindex="0"><code id="embed-code">&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>
+ </div>
+ <a class="text-link" href="https://github.com/shinshin86/mesh-avatar-studio/tree/main/packages/element">Read the package guide ↗</a>
+ </section>
+ <div class="embed-layout">
+ <section class="embed-stage" aria-label="Avatar preview">
+ <mesh-avatar src="%BASE_URL%miko.mavatar" label="Miko"></mesh-avatar>
+ <p id="source-name">Miko</p>
+ <p id="status" role="status" data-state="loading">Loading avatar…</p>
+ </section>
+ <div class="embed-panels">
+ <section class="control-panel">
+ <h2>Avatar file</h2>
+ <label for="avatar-file">Choose a .mavatar file</label>
+ <input id="avatar-file" type="file" accept=".mavatar">
+ <button id="restore-miko" type="button">Return to Miko</button>
+ </section>
+ <fieldset id="avatar-controls" disabled>
+ <legend class="sr-only">Avatar controls</legend>
+ <section class="control-panel">
+ <h2>Expressions</h2>
+ <div class="expression-chips" role="group" aria-label="Expressions">
+ <button type="button" data-expression="neutral" aria-pressed="true">Neutral</button>
+ <button type="button" data-expression="smile" aria-pressed="false">Smile</button>
+ <button type="button" data-expression="shy" aria-pressed="false">Shy</button>
+ <button type="button" data-expression="surprise" aria-pressed="false">Surprise</button>
+ <button type="button" data-expression="halfLidded" aria-pressed="false">Half-lidded</button>
+ <button type="button" data-expression="angry" aria-pressed="false">Angry</button>
+ <button type="button" data-expression="sad" aria-pressed="false">Sad</button>
+ <button type="button" data-expression="wink" aria-pressed="false">Wink</button>
+ </div>
+ <label for="emotion">Emotion</label>
+ <select id="emotion"><option value="">None</option><option value="happy">Happy</option><option value="sad">Sad</option><option value="angry">Angry</option><option value="surprised">Surprised</option><option value="relaxed">Relaxed</option><option value="neutral">Neutral</option></select>
+ <label class="check"><input id="paused" type="checkbox">Pause animation</label>
+ <label class="check"><input id="no-idle" type="checkbox">Disable idle motion</label>
+ </section>
+ <section class="control-panel">
+ <h2>Text lip sync</h2>
+ <form id="speech-form">
+ <label for="speech-text">Japanese text</label>
+ <input id="speech-text" type="text" value="こんにちは" maxlength="300">
+ <button type="submit">Animate speech</button>
+ </form>
+ <p class="hint">Mouth animation only. No voice is generated.</p>
+ </section>
+ <section class="control-panel">
+ <h2>Audio lip sync</h2>
+ <label for="audio-file">Choose an audio file</label>
+ <input id="audio-file" type="file" accept="audio/*">
+ <audio controls aria-label="Audio lip sync"></audio>
+ <button id="microphone" type="button" aria-pressed="false" data-start="Start microphone" data-stop="Stop microphone">Start microphone</button>
+ </section>
+ </fieldset>
+ <p id="notice" role="status"></p>
+ <p class="embed-privacy">Avatar files, audio files and microphone audio are processed in your browser and are not uploaded.</p>
+ </div>
+ </div>
+ </main>
+ <footer class="site-footer shell">
+ <p>Miko © Yuki Shindo (AITuber OnAir). <a href="https://miko.aituberonair.com/#terms">Miko character guidelines</a></p>
+ </footer>
+ </body>
+</html>
diff --git a/site/index.html b/site/index.html
index 784d692..07a38c3 100644
--- a/site/index.html
+++ b/site/index.html
@@ -211,7 +211,7 @@
&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>
+ <p class="section-note"><a href="./embed/">Try the interactive demo</a> · <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">
diff --git a/site/ja/embed/index.html b/site/ja/embed/index.html
new file mode 100644
index 0000000..565305c
--- /dev/null
+++ b/site/ja/embed/index.html
@@ -0,0 +1,98 @@
+<!doctype html>
+<html lang="ja">
+ <head>
+ <meta charset="UTF-8">
+ <meta name="viewport" content="width=device-width, initial-scale=1">
+ <meta http-equiv="Content-Security-Policy" content="connect-src 'self' blob: data: ws://127.0.0.1:* ws://localhost:*; img-src 'self' blob: data:; media-src 'self' blob:; object-src 'none'; base-uri 'self'">
+ <meta name="description" content="表情や口パクを試したり、自分のアバターを表示したりできます。src 属性を省くと、同じ Miko が GitHub Pages から読み込まれます。">
+ <title>Mesh Avatar — HTML の埋め込みを試す</title>
+ <link rel="canonical" href="https://shinshin86.github.io/mesh-avatar-studio/ja/embed/">
+ <link rel="alternate" hreflang="en" href="https://shinshin86.github.io/mesh-avatar-studio/embed/">
+ <link rel="alternate" hreflang="ja" href="https://shinshin86.github.io/mesh-avatar-studio/ja/embed/">
+ <link rel="alternate" hreflang="x-default" href="https://shinshin86.github.io/mesh-avatar-studio/embed/">
+ <link rel="icon" href="/favicon.svg" type="image/svg+xml">
+ <link rel="apple-touch-icon" href="/apple-touch-icon.png">
+ <script type="module" src="/src/embed/main.ts"></script>
+ </head>
+ <body class="embed-page">
+ <header class="site-header shell">
+ <a class="brand" href="../">Mesh Avatar Studio</a>
+ <nav class="primary-nav" aria-label="ページの案内">
+ <a class="header-link" href="../">ホーム</a>
+ <a class="header-link language-switch" href="../../embed/" lang="en">English</a>
+ </nav>
+ </header>
+ <main id="embed-playground" class="shell" data-loading="読み込み中…" data-ready="アバターを読み込みました" data-error="読み込めませんでした。別のファイルを選ぶか、Miko に戻してください。" data-audio-error="この音声ファイルを再生できませんでした。" data-mic-error="マイクを開始できませんでした。ブラウザのアクセス許可を確認し、HTTPS または localhost で開いてください。" data-copy-error="上のコードを選択してコピーしてください。">
+ <section class="intro" aria-labelledby="embed-title">
+ <p class="eyebrow">mesh-avatar-element</p>
+ <h1 id="embed-title">HTML の埋め込みを試す</h1>
+ <p>表情や口パクを試したり、自分のアバターを表示したりできます。src 属性を省くと、同じ Miko が GitHub Pages から読み込まれます。</p>
+ <div class="code-card">
+ <div class="code-heading">
+ <h2>自分のページに埋め込む <span>HTML</span></h2>
+ <button id="copy-snippet" type="button" class="copy-button" data-copied="コピー済み">コピー</button>
+ </div>
+ <pre tabindex="0"><code id="embed-code">&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>
+ </div>
+ <a class="text-link" href="https://github.com/shinshin86/mesh-avatar-studio/tree/main/packages/element">使い方を見る(英語) ↗</a>
+ </section>
+ <div class="embed-layout">
+ <section class="embed-stage" aria-label="アバターのプレビュー">
+ <mesh-avatar src="%BASE_URL%miko.mavatar" label="Miko"></mesh-avatar>
+ <p id="source-name">Miko</p>
+ <p id="status" role="status" data-state="loading">読み込み中…</p>
+ </section>
+ <div class="embed-panels">
+ <section class="control-panel">
+ <h2>アバター</h2>
+ <label for="avatar-file">.mavatar ファイルを選ぶ</label>
+ <input id="avatar-file" type="file" accept=".mavatar">
+ <button id="restore-miko" type="button">Miko に戻す</button>
+ </section>
+ <fieldset id="avatar-controls" disabled>
+ <legend class="sr-only">アバターの操作</legend>
+ <section class="control-panel">
+ <h2>表情</h2>
+ <div class="expression-chips" role="group" aria-label="表情">
+ <button type="button" data-expression="neutral" aria-pressed="true">ふつう</button>
+ <button type="button" data-expression="smile" aria-pressed="false">笑顔</button>
+ <button type="button" data-expression="shy" aria-pressed="false">照れ</button>
+ <button type="button" data-expression="surprise" aria-pressed="false">驚き</button>
+ <button type="button" data-expression="halfLidded" aria-pressed="false">半目</button>
+ <button type="button" data-expression="angry" aria-pressed="false">怒り</button>
+ <button type="button" data-expression="sad" aria-pressed="false">悲しみ</button>
+ <button type="button" data-expression="wink" aria-pressed="false">ウインク</button>
+ </div>
+ <label for="emotion">感情</label>
+ <select id="emotion"><option value="">指定なし</option><option value="happy">喜び</option><option value="sad">悲しみ</option><option value="angry">怒り</option><option value="surprised">驚き</option><option value="relaxed">リラックス</option><option value="neutral">ふつう</option></select>
+ <label class="check"><input id="paused" type="checkbox">動きを止める</label>
+ <label class="check"><input id="no-idle" type="checkbox">待機動作を使わない</label>
+ </section>
+ <section class="control-panel">
+ <h2>文章で口を動かす</h2>
+ <form id="speech-form">
+ <label for="speech-text">日本語の文章</label>
+ <input id="speech-text" type="text" value="こんにちは" maxlength="300">
+ <button type="submit">口を動かす</button>
+ </form>
+ <p class="hint">口の動きだけを試せます。音声は流れません。</p>
+ </section>
+ <section class="control-panel">
+ <h2>音声に合わせて口を動かす</h2>
+ <label for="audio-file">音声ファイルを選ぶ</label>
+ <input id="audio-file" type="file" accept="audio/*">
+ <audio controls aria-label="音声に合わせて口を動かす"></audio>
+ <button id="microphone" type="button" aria-pressed="false" data-start="マイクを開始" data-stop="マイクを停止">マイクを開始</button>
+ </section>
+ </fieldset>
+ <p id="notice" role="status"></p>
+ <p class="embed-privacy">選んだアバターや音声ファイル、マイクの音声はブラウザ内で処理し、外部には送信しません。</p>
+ </div>
+ </div>
+ </main>
+ <footer class="site-footer shell">
+ <p>Miko © Yuki Shindo (AITuber OnAir). <a href="https://miko.aituberonair.com/#terms">Miko キャラクター利用ガイドライン</a></p>
+ </footer>
+ </body>
+</html>
diff --git a/site/ja/index.html b/site/ja/index.html
index 67333d9..8d15a48 100644
--- a/site/ja/index.html
+++ b/site/ja/index.html
@@ -211,7 +211,7 @@
&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>
+ <p class="section-note"><a href="./embed/">デモで試す</a> · <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">
diff --git a/site/src/embed/main.ts b/site/src/embed/main.ts
new file mode 100644
index 0000000..a06e0f9
--- /dev/null
+++ b/site/src/embed/main.ts
@@ -0,0 +1,8 @@
+import '../../../packages/element/src/index';
+import '../style.css';
+import './style.css';
+import { setupPlayground } from './playground.js';
+
+setupPlayground(document.querySelector('#embed-playground')!, {
+ sampleURL: `${import.meta.env.BASE_URL}miko.mavatar`,
+});
diff --git a/site/src/embed/playground.js b/site/src/embed/playground.js
new file mode 100644
index 0000000..e69f014
--- /dev/null
+++ b/site/src/embed/playground.js
@@ -0,0 +1,207 @@
+// Kept inline in the standalone example so it can also open directly from disk.
+export function setupPlayground(root, { sampleURL }) {
+ const el = root.querySelector('mesh-avatar');
+ const status = root.querySelector('#status');
+ const sourceName = root.querySelector('#source-name');
+ const controls = root.querySelector('#avatar-controls');
+ const audio = root.querySelector('audio');
+ const micButton = root.querySelector('#microphone');
+ const notice = root.querySelector('#notice');
+ let context;
+ let audioAnalyser;
+ let audioURL;
+ let microphone;
+ let microphoneSource;
+ let microphoneRequest = 0;
+ let voiceFrame = 0;
+
+ function stopVoice() {
+ cancelAnimationFrame(voiceFrame);
+ voiceFrame = 0;
+ el.avatar?.setSpeaking(false);
+ el.setVoiceLevel(0);
+ }
+
+ function stopMicrophone() {
+ microphoneRequest++;
+ microphone?.getTracks().forEach(track => track.stop());
+ microphone = undefined;
+ microphoneSource?.disconnect();
+ microphoneSource = undefined;
+ micButton.disabled = false;
+ micButton.textContent = micButton.dataset.start;
+ micButton.setAttribute('aria-pressed', 'false');
+ stopVoice();
+ }
+
+ function followVolume(analyser) {
+ stopVoice();
+ el.avatar?.stopLipSync();
+ el.avatar?.setSpeaking(true);
+ const data = new Float32Array(analyser.fftSize);
+ const frame = () => {
+ analyser.getFloatTimeDomainData(data);
+ const rms = Math.sqrt(data.reduce((sum, value) => sum + value * value, 0) / data.length);
+ el.setVoiceLevel(Math.min(1, rms * 5));
+ voiceFrame = requestAnimationFrame(frame);
+ };
+ frame();
+ }
+
+ function audioContext() {
+ context ??= new AudioContext();
+ return context;
+ }
+
+ function loading(name) {
+ audio.pause();
+ stopMicrophone();
+ sourceName.textContent = name;
+ status.textContent = root.dataset.loading;
+ status.dataset.state = 'loading';
+ controls.disabled = true;
+ notice.textContent = '';
+ }
+
+ function ready() {
+ status.textContent = root.dataset.ready;
+ status.dataset.state = 'ready';
+ controls.disabled = false;
+ }
+
+ el.addEventListener('load', ready);
+ el.addEventListener('error', () => {
+ status.textContent = root.dataset.error;
+ status.dataset.state = 'error';
+ controls.disabled = true;
+ });
+ // Also cover callers that initialize controls after the avatar has loaded.
+ if (el.avatar) ready();
+
+ for (const button of root.querySelectorAll('[data-expression]')) {
+ button.addEventListener('click', () => {
+ el.expression = button.dataset.expression;
+ for (const chip of root.querySelectorAll('[data-expression]')) {
+ chip.setAttribute('aria-pressed', String(chip === button));
+ }
+ });
+ }
+ root.querySelector('#emotion').addEventListener('change', event => {
+ el.emotion = event.target.value || null;
+ });
+ root.querySelector('#paused').addEventListener('change', event => {
+ el.paused = event.target.checked;
+ });
+ root.querySelector('#no-idle').addEventListener('change', event => {
+ el.toggleAttribute('no-idle', event.target.checked);
+ });
+
+ root.querySelector('#speech-form').addEventListener('submit', event => {
+ event.preventDefault();
+ audio.pause();
+ stopMicrophone();
+ void el.speak(root.querySelector('#speech-text').value).catch(() => {
+ notice.textContent = root.dataset.error;
+ });
+ });
+
+ root.querySelector('#avatar-file').addEventListener('change', event => {
+ const file = event.target.files?.[0];
+ if (!file) return;
+ loading(file.name);
+ void el.load(file).catch(() => {});
+ event.target.value = '';
+ });
+ root.querySelector('#restore-miko').addEventListener('click', () => {
+ loading('Miko');
+ // Setting an unchanged src or removing an absent attribute would not reload.
+ void el.load(sampleURL).catch(() => {});
+ root.querySelector('#avatar-file').value = '';
+ });
+
+ root.querySelector('#audio-file').addEventListener('change', event => {
+ const file = event.target.files?.[0];
+ if (!file) return;
+ audio.pause();
+ stopMicrophone();
+ if (audioURL) URL.revokeObjectURL(audioURL);
+ audioURL = URL.createObjectURL(file);
+ audio.src = audioURL;
+ notice.textContent = '';
+ });
+ audio.addEventListener('play', async () => {
+ stopMicrophone();
+ try {
+ const ctx = audioContext();
+ audioAnalyser ??= ctx.createAnalyser();
+ if (!audio.dataset.connected) {
+ ctx.createMediaElementSource(audio).connect(audioAnalyser);
+ audioAnalyser.connect(ctx.destination);
+ audio.dataset.connected = 'true';
+ }
+ await ctx.resume();
+ if (!audio.paused && !audio.ended) followVolume(audioAnalyser);
+ } catch {
+ audio.pause();
+ notice.textContent = root.dataset.audioError;
+ }
+ });
+ for (const event of ['pause', 'ended']) audio.addEventListener(event, () => {
+ if (!microphone) stopVoice();
+ });
+ audio.addEventListener('error', () => {
+ if (audio.getAttribute('src')) notice.textContent = root.dataset.audioError;
+ if (!microphone) stopVoice();
+ });
+
+ micButton.addEventListener('click', async () => {
+ if (microphone) {
+ stopMicrophone();
+ return;
+ }
+ audio.pause();
+ stopVoice();
+ notice.textContent = '';
+ const request = ++microphoneRequest;
+ micButton.disabled = true;
+ try {
+ const ctx = audioContext();
+ await ctx.resume();
+ const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
+ if (request !== microphoneRequest) {
+ stream.getTracks().forEach(track => track.stop());
+ return;
+ }
+ microphone = stream;
+ const analyser = ctx.createAnalyser();
+ microphoneSource = ctx.createMediaStreamSource(stream);
+ microphoneSource.connect(analyser);
+ followVolume(analyser);
+ micButton.textContent = micButton.dataset.stop;
+ micButton.setAttribute('aria-pressed', 'true');
+ } catch {
+ if (request === microphoneRequest) {
+ stopMicrophone();
+ notice.textContent = root.dataset.micError;
+ }
+ } finally {
+ if (request === microphoneRequest) micButton.disabled = false;
+ }
+ });
+
+ root.querySelector('#copy-snippet')?.addEventListener('click', async event => {
+ try {
+ await navigator.clipboard.writeText(root.querySelector('#embed-code').textContent);
+ event.target.textContent = event.target.dataset.copied;
+ } catch {
+ notice.textContent = root.dataset.copyError;
+ }
+ });
+
+ window.addEventListener('pagehide', () => {
+ audio.pause();
+ stopMicrophone();
+ if (audioURL) URL.revokeObjectURL(audioURL);
+ if (context) void context.close();
+ }, { once: true });
+}
diff --git a/site/src/embed/style.css b/site/src/embed/style.css
new file mode 100644
index 0000000..e062b50
--- /dev/null
+++ b/site/src/embed/style.css
@@ -0,0 +1,39 @@
+.embed-page { padding-bottom: 40px; }
+.embed-page .site-header { min-height: 76px; }
+.embed-page .intro { padding-block: 36px 24px; }
+.embed-page h1 { font-size: clamp(30px, 4vw, 44px); letter-spacing: -1px; line-height: 1.25; }
+.embed-page .intro > p { max-width: 780px; color: var(--muted); line-height: 1.7; }
+.embed-page .code-card { margin-block: 16px; }
+.embed-page .code-card pre { padding-block: 12px; }
+.embed-layout { display: grid; grid-template-columns: minmax(240px, .8fr) minmax(0, 1.2fr); gap: 24px; align-items: start; margin-top: 28px; }
+.embed-stage, .control-panel { min-width: 0; padding: 20px; border: 1px solid var(--line); border-radius: 12px; background: var(--surface); }
+.embed-stage { position: sticky; top: 20px; text-align: center; }
+.embed-stage mesh-avatar { width: min(100%, 340px); margin: auto; background: #f7f9fc; border-radius: 8px; }
+.embed-stage #status { margin-bottom: 0; font-size: 14px; color: var(--muted); }
+.embed-stage #status[data-state='error'], #notice { color: #a52b2b; }
+.embed-stage #source-name { margin: 12px 0 0; font-size: 13px; overflow-wrap: anywhere; }
+.embed-panels { display: grid; gap: 16px; min-width: 0; }
+.control-panel h2, .control-panel legend { margin: 0 0 16px; font-size: 18px; font-weight: 650; letter-spacing: 0; }
+.control-panel label { display: block; margin-block: 12px 8px; font-size: 14px; }
+.control-panel .check { display: flex; align-items: center; gap: 8px; }
+.control-panel input[type='file'] { display: block; width: 100%; font-size: 13px; margin-bottom: 12px; }
+.control-panel input[type='text'], .control-panel select { width: 100%; min-height: 40px; padding: 8px 10px; border: 1px solid var(--line); border-radius: 6px; font: inherit; background: white; color: var(--ink); }
+.control-panel button { min-height: 40px; padding: 8px 12px; border: 1px solid var(--line); border-radius: 8px; background: white; color: var(--ink); cursor: pointer; }
+.control-panel button:hover:not(:disabled), .control-panel button[aria-pressed='true'] { border-color: var(--accent); color: var(--accent); background: var(--accent-soft); }
+.control-panel button:disabled { opacity: .5; cursor: default; }
+.control-panel audio { display: block; width: 100%; margin-block: 12px; }
+.control-panel form button { margin-top: 12px; }
+.control-panel .expression-chips { margin-bottom: 16px; }
+.control-panel .expression-chips button { flex: 0 0 auto; white-space: nowrap; }
+.control-panel .hint, .embed-privacy { color: var(--muted); font-size: 13px; line-height: 1.7; }
+#avatar-controls { display: grid; gap: 16px; }
+#notice { margin: 0; font-size: 14px; line-height: 1.6; }
+.embed-page input:focus-visible, .embed-page select:focus-visible { outline: 3px solid var(--accent); outline-offset: 3px; }
+@media (max-width: 760px) {
+ .embed-page .shell { width: calc(100% - 32px); }
+ .embed-page .site-header { flex-wrap: wrap; padding-block: 16px; }
+ .embed-page .primary-nav { gap: 16px; }
+ .embed-layout { grid-template-columns: 1fr; }
+ .embed-stage { position: static; }
+ .embed-stage mesh-avatar { width: min(100%, 270px); }
+}
diff --git a/site/vite.config.ts b/site/vite.config.ts
index 3b255f7..b2a23a5 100644
--- a/site/vite.config.ts
+++ b/site/vite.config.ts
@@ -96,6 +96,8 @@ export default defineConfig({
ja: fromHere('./ja/index.html'),
play: fromHere('./play/index.html'),
'ja-play': fromHere('./ja/play/index.html'),
+ embed: fromHere('./embed/index.html'),
+ 'ja-embed': fromHere('./ja/embed/index.html'),
},
output: { banner: `/*! fflate\n${fflateLicense}\n*/` },
},