Build an Online Drawing Board in JavaScript
Create your own online whiteboard with HTML, CSS and JavaScript: draw with a mouse, finger or stylus, pick colors, erase, undo and save your artwork as an image. Try the live demo, then copy the full source code.
Why Build Your Own Online Whiteboard?
Drawing surfaces are part of many apps today, from design tools such as Canva and Sketch.io to classroom and meeting software. Plenty of ready-made online whiteboards exist, and whiteboards online are easy to find, but none of them can be customized to behave exactly the way you want. Building your own gives you a place to add the components you need, and it teaches you how every whiteboard online actually works.
Need a binary tree sketch? Add a function that places nodes on the canvas. Need a neural network diagram? Draw one from a configuration. In this article you will build the foundation: a free online whiteboard that runs in any browser and that you can personalize however you like.
What the finished board does
- Draws with any input: mouse, touch screen or stylus, using pointer events.
- Offers colors and brush sizes: seven presets, a custom color picker and a size slider.
- Erases and undoes: an eraser tool and a stroke-by-stroke undo button.
- Saves your work: download the drawing as a PNG image.
- Adapts to any screen: the canvas resizes on phones, tablets and desktops without losing your drawing.
Step 0: Create the Requirements
Make one HTML file, one CSS file and one JavaScript file, and link them together. We use the names index.html, style.css and app.js. Keeping the three languages in separate files makes each part easier to read and change.
The steps below show the complete code for each file. Because the structure comes first, we start with the HTML, then add the CSS and finish with the JavaScript that brings the board to life.
Step 1: The HTML Code
The page has three parts: a heading, a toolbar and the canvas. Unlike the original fixed 800 by 600 canvas, this canvas has no width or height attributes in the markup, because the CSS and JavaScript will size it to fit the screen. The toolbar uses real button elements so every color and tool works with a keyboard and a screen reader.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Free Drawing Board</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<main class="container">
<h1 class="titre">Online Drawing Board</h1>
<div class="toolbar">
<div id="color-options">
<button class="color-option selected" data-color="#000000" style="background:#000000" aria-label="Black"></button>
<button class="color-option" data-color="#ff0000" style="background:#ff0000" aria-label="Red"></button>
<button class="color-option" data-color="#00ff00" style="background:#00ff00" aria-label="Green"></button>
<button class="color-option" data-color="#0000ff" style="background:#0000ff" aria-label="Blue"></button>
<button class="color-option" data-color="#ffff00" style="background:#ffff00" aria-label="Yellow"></button>
<button class="color-option" data-color="#ff00ff" style="background:#ff00ff" aria-label="Magenta"></button>
<button class="color-option" data-color="#00ffff" style="background:#00ffff" aria-label="Cyan"></button>
<input type="color" id="custom-color" value="#000000" aria-label="Custom color">
</div>
<label>Size <input type="range" id="size" min="1" max="40" value="5"></label>
<button id="eraser-btn">Eraser</button>
<button id="undo-btn">Undo</button>
<button id="clear-btn">Clear</button>
<button id="save-btn">Save PNG</button>
</div>
<canvas id="drawing-board"></canvas>
</main>
<script src="app.js"></script>
</body>
</html>Step 2: The CSS Code
The container centers everything and limits the width, while the canvas fills that width and keeps a 4:3 shape. The most important line is touch-action: none. Without it, dragging a finger across the canvas scrolls the page instead of drawing.
body {
margin: 0;
padding: 16px;
font-family: Arial, sans-serif;
}
.container {
max-width: 900px;
margin: 0 auto;
text-align: center;
}
.titre {
color: #154415;
font-size: clamp(1.8rem, 6vw, 3.6rem);
}
.toolbar {
display: flex;
flex-wrap: wrap;
justify-content: center;
align-items: center;
gap: 10px;
margin-bottom: 12px;
}
#color-options { display: flex; gap: 6px; align-items: center; }
.color-option {
width: 28px;
height: 28px;
border: 1px solid #ccc;
border-radius: 50%;
cursor: pointer;
}
.color-option.selected { border: 3px solid #000; }
button {
min-height: 40px;
padding: 8px 16px;
border: 0;
border-radius: 30px;
background: #154415;
color: #fff;
font-size: 1rem;
cursor: pointer;
}
#drawing-board {
display: block;
width: 100%;
aspect-ratio: 4 / 3;
background: #fff;
border: 1px solid #ccc;
touch-action: none;
cursor: crosshair;
}Step 3: The JavaScript Code
At its core, whiteboard drawing comes down to three ideas: listen to pointer events, turn pointer positions into points on the canvas, and connect those points with lines. Instead of painting directly and forgetting what was drawn, this version stores every stroke as a list of points. Keeping the strokes makes undo trivial and lets the board redraw itself after a resize.
mousedown and mousemove only, so it did nothing on phones and tablets. It also measured positions with pageX - offsetLeft, which drifts when the page scrolls or the canvas is centered, and it used a fixed 800 by 600 canvas that overflowed small screens. This version uses pointer events, getBoundingClientRect() for accurate positions, and a canvas that scales to its container.const canvas = document.getElementById('drawing-board');
const ctx = canvas.getContext('2d');
let color = '#000000';
let size = 5;
let erasing = false;
let strokes = []; // every finished stroke, so we can undo and redraw
let current = null; // the stroke being drawn right now
// Points and sizes are stored relative to the canvas width,
// so the drawing scales when the screen size changes.
const width = () => canvas.getBoundingClientRect().width;
function resize() {
const ratio = window.devicePixelRatio || 1;
const rect = canvas.getBoundingClientRect();
canvas.width = Math.round(rect.width * ratio);
canvas.height = Math.round(rect.height * ratio);
ctx.setTransform(ratio, 0, 0, ratio, 0, 0);
redraw();
}
function toPoint(e) {
const rect = canvas.getBoundingClientRect();
return { x: (e.clientX - rect.left) / rect.width,
y: (e.clientY - rect.top) / rect.width };
}
function setStyle(s) {
ctx.strokeStyle = s.color;
ctx.lineWidth = s.size * width();
ctx.lineCap = 'round';
ctx.lineJoin = 'round';
}
function drawSegment(s, a, b) {
const w = width();
setStyle(s);
ctx.beginPath();
ctx.moveTo(a.x * w, a.y * w);
ctx.lineTo(b.x * w, b.y * w);
ctx.stroke();
}
function redraw() {
const rect = canvas.getBoundingClientRect();
ctx.fillStyle = '#ffffff';
ctx.fillRect(0, 0, rect.width, rect.height);
strokes.forEach((s) => {
s.points.forEach((p, i) => drawSegment(s, s.points[Math.max(i - 1, 0)], p));
});
}
function start(e) {
canvas.setPointerCapture(e.pointerId);
const p = toPoint(e);
current = {
color: erasing ? '#ffffff' : color,
size: size / width(),
points: [p]
};
strokes.push(current);
drawSegment(current, p, p); // a single tap draws a dot
}
function move(e) {
if (!current) return;
const p = toPoint(e);
drawSegment(current, current.points[current.points.length - 1], p);
current.points.push(p);
}
function stop() { current = null; }
canvas.addEventListener('pointerdown', start);
canvas.addEventListener('pointermove', move);
canvas.addEventListener('pointerup', stop);
canvas.addEventListener('pointercancel', stop);
// Tools
document.querySelectorAll('.color-option').forEach((btn) => {
btn.addEventListener('click', () => {
document.querySelectorAll('.color-option').forEach((b) => b.classList.remove('selected'));
btn.classList.add('selected');
color = btn.dataset.color;
erasing = false;
});
});
document.getElementById('custom-color').addEventListener('input', (e) => {
color = e.target.value;
erasing = false;
});
document.getElementById('size').addEventListener('input', (e) => { size = +e.target.value; });
document.getElementById('eraser-btn').addEventListener('click', () => { erasing = !erasing; });
document.getElementById('undo-btn').addEventListener('click', () => { strokes.pop(); redraw(); });
document.getElementById('clear-btn').addEventListener('click', () => { strokes = []; redraw(); });
document.getElementById('save-btn').addEventListener('click', () => {
const a = document.createElement('a');
a.download = 'drawing.png';
a.href = canvas.toDataURL('image/png');
a.click();
});
window.addEventListener('resize', resize);
resize();How it works
Each press creates a stroke object with a color, a size and a list of points. While the pointer moves, the code draws only the newest line segment, which keeps drawing fast. Undo removes the last stroke and redraws the rest, and a resize recalculates the canvas resolution (including for high-density screens) and replays every stroke at the new scale.
This is the core of any whiteboard online drawing tool. Features such as shapes, text or a binary tree sketch are just new kinds of items added to the same list.
Live Demo: Free Drawing Board in Action
This demo uses the same logic as the code above. Draw with your mouse, finger or stylus, change colors and sizes, erase, undo, or save your picture. Nothing is uploaded; your drawing stays in your browser.
Ideas to Extend Your Whiteboard
Once the basics work, these features turn a simple board into a more complete tool:
- Shapes and text: add rectangles, circles, arrows and text boxes as new stroke types.
- Component sketches: write functions that draw a binary tree from an array like
['H', 'E', 'L', 'L', 'O'], or a neural network from a layer configuration. - Redo and keyboard shortcuts: keep a second stack for redo and bind
Ctrl+Z. - Saved boards: store the strokes array as JSON in localStorage and reload it later.
- Pressure and smoothing: use
e.pressurefrom pen input to vary line width and smooth the lines. - Real-time sharing: to build an online drawing board together with other people, send each stroke to a server over WebSockets and replay it on every connected screen.
JavaScript Exercises Using the Drawing Board
This project is a great source of javascript exercises for beginners because every feature maps to a core concept: variables hold the color and size, functions handle each tool, and events connect the user to the canvas. If you want javascript exercises and solutions to compare against, rebuild each tool from scratch before you look at the code above.
Variables and functions
Begin with javascript variables exercises: change the starting color and brush size, and see how the stored values affect every new stroke. Then try javascript function exercises by turning repeated code into small functions, for example one that draws a rectangle or one that resets the tool state.
Challenges to try next
These javascript practice exercises with solutions are easy to check, because the live demo shows the expected behavior. Treat them as javascript tasks for practice, or as quick js exercises for a single sitting:
- Add a redo button that restores the last undone stroke.
- Add a background color picker for the canvas.
- Draw a straight line tool using the start and end points.
- Show the current brush size as a circle that follows the pointer.
For more javascript exercises, browse our JavaScript projects.
Frequently Asked Questions
How does a draw board online work in the browser?
The HTML canvas gives you a grid of pixels you can paint with JavaScript. The page listens for pointer events, converts each position to canvas coordinates, and draws lines between the points. Everything runs locally in the browser.
Does this work on phones and tablets?
Yes. The code uses pointer events, which cover mouse, touch and stylus input, and the CSS rule touch-action: none stops the page from scrolling while you draw. The canvas also resizes to fit any screen.
Is it really a free online whiteboard?
The code on this page is free to use and customize, and the demo runs entirely in your browser with no sign-up. For a whiteboard online free of any account or server, you can host the three files on any static website.
Can several people draw on the same board?
Not with this version, because the strokes live only in one browser. Sharing a board needs a server that relays each stroke to everyone, usually with WebSockets, which makes a good next project.
Is JavaScript hard for beginners?
It has a gentle start because you see results immediately in the browser. Visual projects like this board are a motivating way to learn events, functions and the DOM.
Keep Creating with JavaScript
In conclusion, building an Online Drawing Board with JavaScript Source Code is a rewarding way to learn how interactive web apps work. You set up a canvas, handled pointer input, stored strokes so you could undo and resize, and added tools for color, size, erasing and saving, all with plain HTML, CSS and JavaScript.
The same ideas power professional board drawing online tools, so every feature you add brings you closer to how they work. Whether you want a classroom helper, a sketchpad or a base for your own diagram editor, this board is a solid starting point. Pick up your virtual brush and keep experimenting.
