Avatars

Rendering an avatar

The 2D layer stack, the 3D scene on top of it, the camera, and a picture a fan can download.

Showing a fan their avatar. Start with the 2D stack, because you need it either way, then put the 3D scene in front of it.

The shape

import { Avatar, useAvatar } from '@xborglabs/fanbase-react'

export function AvatarPanel() {
  return (
    <Avatar.Provider>
      <AvatarView />
    </Avatar.Provider>
  )
}

function AvatarView() {
  const { state } = useAvatar()

  if (state.reason === 'AUTH_REQUIRED') return <SignInPrompt />
  if (state.reason === 'AVATAR_DISABLED') return null
  if (state.isLoading) return <AvatarSkeleton />

  return <AvatarStage />
}

Avatar.Provider reads the fan's slots once and holds them. It takes no props to get started: the community comes from FanbaseProvider.

state.reasonMeansShow
AUTH_REQUIREDSigned out. A fan's own avatar needs a session.A sign-in prompt
AVATAR_DISABLEDThe community does not use avatarsNothing

2D: a stack of images

state.layers is the avatar as flat images, in the order to paint them. Put them in one box, each on top of the last.

function AvatarLayers() {
  const { state } = useAvatar()

  return (
    <div style={{ position: 'relative', aspectRatio: state.aspectRatio }}>
      {state.layers.map((layer) => (
        <img
          key={layer.slotId}
          src={layer.url}
          alt=""
          style={{ position: 'absolute', inset: 0, width: '100%', opacity: layer.opacity }}
        />
      ))}
    </div>
  )
}

Keep the order as given. It is what puts a jacket over a shirt and a hat over hair.

state.aspectRatio is width divided by height, taken from the images themselves. Use it and every layer lines up.

3D: the scene

The 3D renderer is a separate import, @xborglabs/fanbase-react/avatar-3d, with dependencies of its own. Install them only if you render an avatar:

npm install three @react-three/fiber @react-three/drei @react-three/postprocessing postprocessing
npm install -D @types/three

Two requirements. The 3D path needs React 19. And three has to be at least 0.177 and below 0.187, which is the range the renderer is built against.

Load the scene lazily and only in the browser, so the 3D engine stays out of your first page load:

// AvatarStage.tsx
import { lazy, Suspense, useState } from 'react'
import { useAvatar } from '@xborglabs/fanbase-react'

const Avatar3DStage = lazy(() => import('./Avatar3DStage'))

export function AvatarStage() {
  const { state } = useAvatar()
  const [failed, setFailed] = useState(false)

  if (!state.is3DEligible || failed) return <AvatarLayers />

  return (
    <Suspense fallback={<AvatarLayers />}>
      <Avatar3DStage onError={() => setFailed(true)} />
    </Suspense>
  )
}
// Avatar3DStage.tsx
import { resolveAvatarZoomTarget, useAvatar, useAvatarSceneConfig } from '@xborglabs/fanbase-react'
import { Avatar3D } from '@xborglabs/fanbase-react/avatar-3d'

export default function Avatar3DStage({ activeSlotId, onError }: { activeSlotId?: string; onError: () => void }) {
  const { state } = useAvatar()
  const { data: config, isPending } = useAvatarSceneConfig()

  if (isPending) return <AvatarLayers />

  return (
    <Avatar3D.Provider config={config}>
      <Avatar3D.Scene
        className="your-avatar-canvas"
        slots={state.slots}
        zoomTarget={resolveAvatarZoomTarget({ slots: state.slots, activeSlotId })}
        onError={onError}
      />
      <Avatar3D.ResetCamera asChild>
        <button type="button" />
      </Avatar3D.ResetCamera>
    </Avatar3D.Provider>
  )
}

In Next.js, use next/dynamic with ssr: false in place of lazy.

When to show which

SituationRender
state.is3DEligible is true and nothing has failedAvatar3D.Scene
state.is3DEligible is falseThe 2D stack. One of the worn items has no 3D model.
onError firedThe 2D stack

onError fires once, for any of three reasons: the browser has no 3D graphics support, the avatar has no 3D body, or a model failed to load. You do not need to tell them apart. Switch to the 2D stack and stay there.

Give it a size

The scene draws into whatever box you give it, on a transparent background, so your page shows behind the avatar. A wrapper with no height renders nothing. Set one through className or style.

While it loads

The models take a moment. useAvatar3D().state.isLoaded is false until the body is on screen. Lay your own spinner over the box until then, or keep the 2D stack visible underneath.

Scene settings come from the community

useAvatarSceneConfig() returns how your community's avatar should look and behave: camera distance, whether a fan can rotate or zoom, the lighting quality. It is set for your community by the FanBase team. Pass it to Avatar3D.Provider as shown, and the scene matches the look you agreed.

The camera

A fan can drag to turn the avatar and scroll or pinch to zoom, when the community's settings allow it.

Framing follows what is being edited. resolveAvatarZoomTarget({ slots, activeSlotId }) returns where to point the camera. Pass the slot the fan is browsing and the camera moves in on it: the feet for boots, the head for headgear. With no active slot it frames the chest.

TargetFrames
allThe whole body
headgearThe head
upper-bodyThe chest. Also the default.
lower-bodyThe legs
bootsThe feet
left-hand, right-handThat hand

Reset appears when it is needed. Avatar3D.ResetCamera renders nothing until the fan has moved the camera, then shows a button that puts it back. Its default label is "Reset Camera".

A picture to download

Avatar3D.Capture takes a picture of the avatar and hands it to you. What you do with it is yours: a download, a share, an upload.

<Avatar3D.Capture asChild onCapture={downloadPng}>
  <button type="button" />
</Avatar3D.Capture>

function downloadPng(blob: Blob) {
  const url = URL.createObjectURL(blob)
  Object.assign(document.createElement('a'), { href: url, download: 'avatar.png' }).click()
  setTimeout(() => URL.revokeObjectURL(url), 0)
}

The picture is the upper body, framed the same way every time, whatever the fan had the camera doing. The default label is "Download".

Both buttons need to sit inside Avatar3D.Provider.

What it loads from elsewhere

Three kinds of file come from outside your own site. If your site sets a Content Security Policy, allow them, or the scene fails and falls back to 2D.

FileFromTo host it yourself
The lighting for the sceneraw.githack.comPass environmentFiles="/your/path.hdr" to Avatar3D.Scene
The decoder for compressed modelswww.gstatic.comPass dracoDecoderPath
The modelsYour community's media hostNot needed

Quality adjusts itself

The scene starts at low quality and steps up when the device keeps up, and back down when it does not. It remembers what worked on that device. There is nothing to configure, and an older phone gets a smooth avatar without the expensive effects.

Components

ComponentUse
Avatar.ProviderReads the fan's slots and holds the draft
Avatar3D.ProviderHolds the camera and capture state for one scene
Avatar3D.SceneThe 3D render
Avatar3D.ResetCameraPuts the camera back, shown only after the fan moves it
Avatar3D.CaptureTakes a picture and hands you the file

The two buttons take asChild and render your element. Full props in Components.

Checklist

  • A signed-out fan sees a sign-in prompt, and a community with avatars off shows nothing
  • The 2D layers are stacked in the order given, in a box with the given aspect ratio
  • The 3D engine is not in the first page load
  • An avatar that cannot render in 3D shows the 2D stack, and so does one whose scene failed
  • The scene has a height
  • The camera moves in on the slot being edited
  • Reset camera appears only after a drag

On this page