Building a Real-Time Collaborative Whiteboard with JavaScript and WebSockets
Learn how to create a real-time collaborative whiteboard using JavaScript and WebSockets. This beginner-friendly tutorial covers setting up a server and client to draw and share sketches live.
In this tutorial, you will learn how to build a real-time collaborative whiteboard application using JavaScript. The goal is to allow multiple users to draw on the same canvas simultaneously and see each other's drawings live. We'll use WebSockets to establish a two-way communication channel between clients and the server.
We'll create a simple WebSocket server with Node.js using the popular `ws` library, and a client side application with HTML5 Canvas and JavaScript to handle drawing and sending coordinates in real-time.
### Step 1: Set up the WebSocket server
Create a new Node.js project and install the `ws` package:
npm init -y
npm install wsNext, create a file named `server.js` and add the following code to start a WebSocket server that broadcasts messages to all connected clients:
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });
wss.on('connection', function connection(ws) {
ws.on('message', function incoming(message) {
// Broadcast incoming message to all clients except sender
wss.clients.forEach(function each(client) {
if (client !== ws && client.readyState === WebSocket.OPEN) {
client.send(message);
}
});
});
ws.send(JSON.stringify({ type: 'info', message: 'Welcome to the collaborative whiteboard!' }));
});
console.log('WebSocket server is running on ws://localhost:8080');This server listens for WebSocket connections on port 8080. When a client sends drawing data, it broadcasts that data to all other connected clients.
### Step 2: Create the HTML and client JavaScript
Create an `index.html` file with a canvas element and some simple styles to fill the screen:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Collaborative Whiteboard</title>
<style>
body, html {
margin: 0;
height: 100%;
overflow: hidden;
}
canvas {
display: block;
background: #fff;
touch-action: none; /* Prevent scrolling on touch devices while drawing */
}
</style>
</head>
<body>
<canvas id="board"></canvas>
<script src="script.js"></script>
</body>
</html>Now, add the drawing and WebSocket client logic in a `script.js` file:
const canvas = document.getElementById('board');
const ctx = canvas.getContext('2d');
// Resize canvas to fill the window
function resize() {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
}
window.addEventListener('resize', resize);
resize();
// Set drawing parameters
ctx.lineWidth = 2;
ctx.lineCap = 'round';
ctx.strokeStyle = '#000';
let drawing = false;
let currentPos = { x: 0, y: 0 };
// Setup WebSocket connection
const socket = new WebSocket('ws://localhost:8080');
socket.addEventListener('open', () => {
console.log('Connected to WebSocket server');
});
socket.addEventListener('message', (event) => {
const data = JSON.parse(event.data);
if(data.type === 'draw') {
drawLine(data.from.x, data.from.y, data.to.x, data.to.y);
}
});
canvas.addEventListener('pointerdown', (event) => {
drawing = true;
currentPos = { x: event.clientX, y: event.clientY };
});
canvas.addEventListener('pointermove', (event) => {
if (!drawing) return;
const newPos = { x: event.clientX, y: event.clientY };
// Draw on local canvas
drawLine(currentPos.x, currentPos.y, newPos.x, newPos.y);
// Send drawing data to server
socket.send(JSON.stringify({
type: 'draw',
from: currentPos,
to: newPos
}));
currentPos = newPos;
});
canvas.addEventListener('pointerup', () => {
drawing = false;
});
canvas.addEventListener('pointerleave', () => {
drawing = false;
});
function drawLine(x1, y1, x2, y2) {
ctx.beginPath();
ctx.moveTo(x1, y1);
ctx.lineTo(x2, y2);
ctx.stroke();
}
### Step 3: Run the server and open the client
Start the WebSocket server by running: bash node server.js Then open the `index.html` file in multiple browser tabs or windows. When you draw on one, the lines will appear in real-time on the others.
### Summary You just built a simple real-time collaborative whiteboard from scratch using JavaScript and WebSockets. This is a great foundation for adding features like user colors, chat, or persistent sessions. Try experimenting with additional functionality to make your whiteboard more powerful!