Dev.to WebDev 🛠 Dev 👁 2 📖 9 min read

Following one stroke: how a multiplayer canvas syncs with Yjs and Konva

I'm building a multiplayer sketch canvas: users open the same link and draw together in real time. I'm a frontend engineer, so React and canvas drawing felt familiar. Real-time sync did not. This post follows one stroke

Following one stroke: how a multiplayer canvas syncs with Yjs and Konva

I'm building a multiplayer sketch canvas: users open the same link and draw together in real time. I'm a frontend engineer, so React and canvas drawing felt familiar. Real-time sync did not.

This post follows one stroke in four steps, from the moment you press the pen down to the moment it appears on your friend's screen: pen down, pen moves, sharing the preview, pen up. Where I measured something, you'll see the number.

You'll learn:

  • why your own line should never wait for the network
  • how to cut about 75% of the points in a slow drag without changing how it looks
  • why Yjs gives you two channels, and what goes in which
  • why two people drawing at once never conflict
  • four things that bit me, so they don't bite you

The setup

  • React + Konva (react-konva) draws the canvas.
  • Yjs holds the drawing as a shared document: a Y.Array of strokes.
  • y-websocket connects every tab to a small Node server, which relays changes between everyone in a room.

A stroke is a plain object:

type Stroke = { kind: 'stroke'; id: string; tool: 'pen' | 'eraser'; color: string; width: number; points: number[] };

points is flat ([x1, y1, x2, y2, …]), the format Konva's <Line> takes directly.

The one fact everything else builds on: every open tab and the server each keep a full copy of the document in memory. The WebSocket is only the pipe between those copies. It stores nothing.

Step 1: pen down, draw locally first

When you press the pen, the line appears on your screen immediately. Nothing waits for the network. That's why drawing feels instant even on a slow connection: only other people's view lags.

The stroke in progress lives in two places:

const currentRef = useRef<number[] | null>(null);
const [current, setCurrent] = useState<number[] | null>(null);

const updateCurrent = (points: number[] | null) => {
  currentRef.current = points; // source of truth: always the newest points
  setCurrent(points);          // makes React re-render the line
  if (points) live.setDrawing({ kind: 'stroke', tool, color, width, points: liveTail(points) });
};

Why both? Event handlers are closures: they see current as it was at the last render. React batches state updates, so several pointer events can arrive before the next render. My first version read current in the pen-up handler. It added back the last raw position (lastRaw, already a ref), so the final point was safe, but any point kept since the last render was not:

render #5        → handlers see current = [A, B]
pointermove (C)  → kept: setCurrent([A, B, C])       // queued, no render yet
pointermove (D)  → kept: setCurrent([A, B, C, D])    // still no render; lastRaw = D
pointerup        → end() saves current + lastRaw = [A, B, D]   ← point C lost

A ref is one mutable box every version of the handler shares, so end() sees [A, B, C, D]. My rule now: state is for what the screen shows, a ref is for what your logic reads right now.

Step 2: pen moves, keep fewer points

The browser fires pointermove 60–120 times a second. A slow drag produces piles of points a fraction of a pixel apart. They look identical on screen, but every one of them is synced to everyone and stored in the document.

So a point is kept only if it is at least 2 screen pixels away from the last kept point:

export function appendIfFar(points: number[], p: Point, minDistance: number): number[] {
  const last = lastPoint(points); // the last point we KEPT
  return Math.hypot(p.x - last.x, p.y - last.y) >= minDistance ? [...points, p.x, p.y] : points;
}

// 2 screen px, converted to canvas units: at 2x zoom that's 1 unit
export const minDistanceFor = (zoom: number) => MIN_POINT_DISTANCE / zoom;

On a slow test drag with 0.5 px steps: 201 pointer positions became 51 stored points (−75%), and the line looks the same. When the pen lifts, the exact final position is added back, so the stroke ends where you let go.

That figure is for a slow drag. A fast stroke, where each step is already longer than 2 px, loses no points at all: the filter only removes points where they pile up.

The detail that matters: compare against the last kept point, not the last raw one. With 0.5 px steps, every raw step is shorter than 2 px, so comparing against the raw point would drop everything. Your slow, wiggly stroke would become a straight line from start to end. Comparing against the kept point lets small steps add up until they're worth storing.

One more cheap win I measured but haven't shipped: rounding coordinates to whole pixels. Yjs stores 347.2851 in about 9 bytes and a small whole number in 2–3, so 50 test strokes went from 92 KB to 33 KB.

Two channels: the document and awareness

This is the idea I wish I'd understood on day one. Yjs gives you two ways to share state, and they behave very differently.

Document (Y.Doc, Y.Array) Awareness
What goes in finished strokes who's here, cursors, the stroke being drawn
How changes combine CRDT merge across every copy each person has one state object; the newest replaces the old
History yes none
Survives a refresh yes no
When someone leaves their strokes stay their state disappears

Why not put cursors in the document? Because they're temporary. The document is built to keep things: a cursor written there stays until someone deletes it. A closed tab would leave its last cursor behind for everyone, and you'd need cleanup code that a crashed tab or a closed laptop never runs. Awareness is built for exactly this: each person has one state object, every update replaces it, and it's removed automatically when they leave (right away on a clean disconnect, after 30 seconds of silence otherwise).

The same goes for the half-drawn stroke. It only matters right now, so it lives in awareness. If your laptop lid closes mid-stroke, it simply disappears for everyone, and the document never sees a half-finished line.

Step 3: share the live stroke, but not on every event

Every awareness change is a message to everyone in the room. Sending one per pointer event would mean 60–120 messages a second per person. So the cursor and the stroke being drawn share one throttle: at most one message every 50 ms (20 per second), both fields in the same message.

const update = (patch: Partial<Live>, immediately: boolean) => {
  latest.current = { ...latest.current, ...patch }; // only remember the newest values
  if (immediately) flush();                         // null (pen up, pointer left): send now
  else if (timer.current === null) timer.current = setTimeout(flush, SEND_EVERY_MS);
};

const flush = () => {
  clearTimeout(timer.current ?? undefined);
  timer.current = null;
  // one setLocalState call = one message, other fields (like `user`) kept
  awareness.setLocalState({ ...awareness.getLocalState(), ...latest.current });
};

Measured: 102 pointer moves became 17 messages.

The subtle part is which updates a throttle drops. The tempting version, "send the first event, ignore the rest for 50 ms", drops the last position when you stop moving. Others then see your cursor frozen a little short of where it really is, and it stays wrong until you move again. This version always sends the latest value when the timer fires. A throttle may drop the middle updates, never the last one.

One caveat: awareness sends the whole state each time, not just what changed. A long stroke is resent in full every 50 ms, so I cap the live preview to the newest part of the stroke (liveTail). The finished stroke still goes to the document complete.

Step 4: pen up, hand the stroke over

When the pen lifts, the stroke moves from awareness (temporary preview) into the document (kept). The order of those two steps matters:

const end = () => {
  const points = currentRef.current ? withFinalPoint(currentRef.current, lastRaw.current) : null;
  if (points && points.length >= 4) {
    strokes.push([{ kind: 'stroke', id: crypto.randomUUID(), tool, color, width, points }]); // 1. document
  }
  if (points) live.setDrawing(null); // 2. clear the preview, sent immediately
  // … reset local state
};

Both messages travel over the same WebSocket, so they arrive in the order they were sent.

  • Document first, then clear: for a split second your friend sees the stroke twice (preview and finished copy on top of each other). Nobody notices.
  • The other way round: there's a gap of one message where the stroke exists nowhere on their screen. It blinks out, then pops back. That's a visible flicker at the end of every stroke.

"Add the new thing before removing the old one" turned out to be a pattern I keep reusing.

One quiet detail: pen-up cancels any pending throttled update, so the last few live points may never be sent as a preview. That's fine, because the preview is a best-effort sketch and the document holds every point.

The whole journey in one picture

One stroke's journey: your tab, the throttle, the server and your friend's tab

Only the preview goes through the throttle. The finished stroke and the "clear preview" message go out immediately, in that order, on the same socket.

What about conflicts?

Two people drawing at once never conflict. Every change has a unique id (client + counter), deletes leave a small marker instead of erasing, and every copy, each tab and the server, merges by the same rules. Changes can arrive in any order and everyone still ends up with the same picture. The server doesn't decide anything.

How that works in detail, and the server-restart experiment that convinced me, is the next post.

What to watch for

  1. Every other client is untrusted. Anything that arrives through awareness or the document can be broken or hostile. My first color check was typeof color === 'string'. A peer could then send url(https://tracker.example/x) as a color. It went into the avatar's CSS background, and every browser in the room fetched that URL, leaking everyone's IP. The fix is to check the format, not just the type: only #rrggbb passes. The same goes for the rest of what other players send. Today the app checks that points are finite numbers, a width is above 0 and at most 200, a live stroke has at most 20,000 coordinates, and names are cut to 24 characters.
  2. No persistence by default. The server keeps rooms in memory. All tabs closed plus a server restart means the drawing is gone. Decide early whether that's fine.
  3. Awareness resends the whole state. Fine for a cursor, heavy for a 2,000-point stroke at 20 messages a second. Keep awareness small, and cap what you put in it.
  4. Two tabs in one browser are two participants. Each tab is its own Yjs client with its own document copy, and that's correct. But "2 online" for one person looks wrong. I added a person id saved in localStorage and count people instead of connections. Keep in mind that anyone can send any id, so it's a display hint, never a permission.

Wrapping up

One stroke, end to end:

  • Your tab draws immediately and keeps only points worth keeping.
  • The throttle turns ~100 pointer events into ~17 messages and always sends the latest one.
  • The server relays and keeps a copy, but never decides anything.
  • Your friend's tab merges by the same rules and ends up with the same picture.

The biggest lesson for me: split "what should last" (the document) from "what's happening right now" (awareness), and most of the hard problems get smaller.

This canvas is the front half of a bigger project: when you hit Generate, a vision model reads the sketch and an image model turns it into a picture. Next in the series: how the merging works in detail (with the server-restart experiment and the other optimizations I made), then turning a sketch into a structured AI brief, and keeping the AI bill under control.

What's your experience with Yjs or other CRDTs? I'd love to hear what bit you.

📰 Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.