Skip to content

A lightweight 2.5D character player for the web, with lip sync and webcam face tracking.

2.2 KB
Raw Blame
<!doctype html>
<html lang="en">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>LivLiv Player in React</title>
<style>
  body { margin: 0; font: 15px/1.5 system-ui, sans-serif; background: #f4f2ef; color: #222; padding: 16px; }
  canvas { display: block; width: 320px; height: 400px; }
  button { margin: 8px 8px 0 0; }
</style>
<script type="importmap">{ "imports": {
  "react": "https://esm.sh/[email protected]",
  "react-dom/client": "https://esm.sh/[email protected]/client"
} }</script>
<div id="root"></div>
<p id="status"></p>
<script type="module">
  // A player in a React component, under StrictMode, which mounts everything twice. One effect owns the player and gives its
  // canvas up on unmount; another loads what the props say. StrictMode's second mount comes in the same task, so the new
  // player keeps the context, and its load replaces the first, which rejects with an AbortError.
  import { StrictMode, createElement as h, useEffect, useRef, useState } from 'react'
  import { createRoot } from 'react-dom/client'
  import { Player } from '../dist/index.js'

  const status = document.getElementById('status')

  function Character({ source }) {
    const canvas = useRef(null), player = useRef(null)
    useEffect(() => {
      const p = player.current = new Player(canvas.current)
      return () => p.dispose({ release: true })
    }, [])
    useEffect(() => {
      player.current.load(source).then(
        (m) => { status.textContent = `${m.name} · ${m.format} ${m.version}` },
        (e) => { if (e.name !== 'AbortError') status.textContent = e.message })
    }, [source])
    return h('canvas', { ref: canvas })
  }

  const CAST = ['k01', 'd03', 'v05']

  function App() {
    const [who, setWho] = useState(0), [on, setOn] = useState(true)
    return h('div', null,
      on && h(Character, { source: `../characters/${CAST[who]}.livliv` }),
      h('button', { id: 'next', onClick: () => setWho((who + 1) % CAST.length) }, 'next character'),
      h('button', { id: 'toggle', onClick: () => setOn(!on) }, on ? 'unmount' : 'mount'))
  }

  createRoot(document.getElementById('root')).render(h(StrictMode, null, h(App)))
  window.__react = true
</script>
</html>