Examples Collaborative cursors

Collaborative cursors

Each visitor writes normalized pointer coordinates to their own signed makeUserState slot, and other connected browsers render them. The live cursors on this site follow the same pattern.

Per-user cursor slots

makeUserState matches cursor tracking closely: each user can only write their own slot, late joiners receive everyone's latest position automatically, and entries are evicted when a user's last tab leaves.

import {joinRoom} from 'trystero'

const room = joinRoom({appId: 'cursors.example.com'}, 'canvas')

const cursor = room.makeUserState('cursor', null)
const profile = room.makeUserState('profile', {name: 'Anon', color: '#c8a87c'})

profile.set({name: promptForName(), color: randomColor()})

window.addEventListener('pointermove', e => {
  cursor.set({
    x: e.clientX / window.innerWidth,
    y: e.clientY / window.innerHeight
  })
})

cursor.onChange((pos, {userId, self, removed}) => {
  if (self) return
  if (removed) {
    removePeerCursor(userId)
    return
  }
  const {name, color} = profile.get(userId)
  renderPeerCursor(userId, pos.x, pos.y, {name, color})
})

window.addEventListener('pointerleave', () => cursor.clear())

set() updates local state synchronously and coalesces rapid writes over a 40 ms window on the wire, so calling it directly from pointermove requires no extra throttling. Interpolate incoming positions in your renderer for smooth movement. Because slots are keyed by userId, opening a second tab in the same browser updates the existing cursor rather than creating a duplicate.

removed: true fires both when a peer calls cursor.clear() (on pointerleave) and when their last tab disconnects.

// Replay existing cursor positions when mounting a view after peers have joined
cursor.onChange(renderFromChange, {replay: true})

Notes

  • For a scrollable document or zoomable canvas, publish coordinates in document or world space rather than viewport percentages.
  • For larger rooms of dozens of participants, pass the experimental scale() plugin to joinRoom(); the cursor code stays unchanged.
  • When testing on a single machine, open a private window or pass identity: 'none' so each window receives a distinct userId.