Here is the core setup connecting a local HTML5 canvas state to a Yjs shared map and WebSocket provider.
canvas/multiplayer_sync.ts (typescript)
import * as Y from 'yjs';
import { WebsocketProvider } from 'y-websocket';
export interface CanvasShape {
id: string;
x: number;
y: number;
width: number;
height: number;
color: string;
}
export class CollaborativeCanvasEngine {
private doc: Y.Doc;
private shapesMap: Y.Map<CanvasShape>;
private provider: WebsocketProvider;
constructor(boardId: string, wsUrl: string) {
this.doc = new Y.Doc();
this.shapesMap = this.doc.getMap<CanvasShape>('shapes');
this.provider = new WebsocketProvider(wsUrl, boardId, this.doc);
this.shapesMap.observe((event) => {
event.changes.keys.forEach((change, key) => {
if (change.action === 'add' || change.action === 'update') {
const updatedShape = this.shapesMap.get(key);
console.log(`Shape ${key} synchronized:`, updatedShape);
}
});
});
}
public updateShapePosition(id: string, x: number, y: number): void {
const existing = this.shapesMap.get(id);
if (existing) {
this.shapesMap.set(id, { ...existing, x, y });
}
}
}