Example

Collaborative cursors with WebRTC actions

Send a small message when the pointer moves, then draw a cursor for each peer. This is the same pattern used by the live cursors on this site.

Broadcast pointer positions

This sketch sends coordinates as fractions of the viewport. The rendering functions and color helper are yours to implement. For a shared canvas or document, use coordinates relative to that surface instead.

import {joinRoom, selfId} from 'trystero'

const room = joinRoom({appId: 'dev.trystero.examples.cursors'}, '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)
}

Pointer events can fire faster than you need to send them. Throttle updates in your app and interpolate received positions for smooth movement. Remove a peer’s cursor when onPeerLeave fires.