Example

Collaborative cursors with WebRTC actions

Cursor presence is a good first Trystero feature: messages are tiny, realtime, and easy to model as a peer-to-peer action.

Broadcast pointer positions

Normalize pointer coordinates before sending them so peers can render the cursor correctly on different screen sizes.

import {joinRoom, selfId} from 'trystero'

const room = joinRoom({appId: 'cursor-demo'}, 'canvas')
const cursor = room.makeAction('cursor')

const peers = new Map()

cursor.onMessage = ({x, y, color}, {peerId}) => {
  peers.set(peerId, {x, y, color})
  renderPeerCursor(peerId, x, y, color)
}

window.onpointermove = e => {
  cursor.send({
    x: e.clientX / window.innerWidth,
    y: e.clientY / window.innerHeight,
    color: colorForPeer(selfId)
  })
}

room.onPeerLeave = peerId => {
  peers.delete(peerId)
  removePeerCursor(peerId)
}