Frontend System Design · Lesson 80 of 86 · 4 min
Rendering Large Datasets: Canvas vs SVG
This is a classic system design question to gauge your understanding of browser rendering trade-offs.
When you need to render thousands of data points, a naive approach of creating one DOM element per point will cripple your application. The browser's rendering engine wasn't built for that. You have two main strategies: either drastically reduce the number of DOM nodes you render at any given time, or avoid creating them for each data point altogether.
For long lists and tables, the first strategy is virtualization. You only render the items currently in the viewport (plus a small buffer), creating the illusion of a complete list by manipulating scroll height and offsets.
For data visualizations, the choice is more fundamental: do you use a DOM-based approach (SVG) or a pixel-based one (Canvas)? This decision dictates performance, interactivity, and accessibility from the start.
SVG: The DOM-based, Interactive Choice
SVG (Scalable Vector Graphics) is a retained-mode graphics system. Every circle, path, and text element you create is a distinct DOM node. You can inspect it in the dev tools, style it with CSS, and attach event listeners directly to it.
This makes it ideal for standard charts and diagrams where interactivity is key. Think of a bar chart where you need to show a tooltip on hover for each bar. With SVG, it's just a mouseover event on a <rect> element. It's also resolution-independent and inherently more accessible.
In an interview, explain that most chart libraries like D3 default to SVG for a reason: it maps cleanly to familiar web development patterns (DOM manipulation, events, CSS) and is perfect for visualizations with hundreds, or even a couple thousand, elements.
The problem is the DOM overhead. Performance falls off a cliff as the number of nodes increases. Once you get into the high thousands of elements, the browser will struggle with layout, styling, and event handling.
Canvas: The High-Performance Pixel Buffer
Canvas is an immediate-mode graphics system. You get a single <canvas> DOM element, which is a blank, raster bitmap. You use a JavaScript API to draw pixels onto it. Once drawn, the browser forgets about the "circle" or "line"; it only knows about the resulting pixels.
This "fire and forget" model is incredibly fast. You can render hundreds of thousands of shapes without the browser breaking a sweat, because you're not creating thousands of DOM nodes. This is your tool for high-density scatter plots, heatmaps, or real-time graphs with constant updates.
The trade-offs are significant. Interactivity is manual; if you want to know if the user clicked a circle, you must write hit-detection logic that maps mouse coordinates to the shapes you've drawn. Accessibility is also manual; a screen reader sees a single image, so you must provide fallbacks or use parallel DOM structures.
The trap: Candidates often forget about high-DPI screens. A canvas will look blurry on a Retina display unless you account for window.devicePixelRatio. You must scale the canvas dimensions and the drawing context. Forgetting this detail shows a lack of production experience.
const dpr = window.devicePixelRatio || 1;
const rect = canvas.getBoundingClientRect();
// Set the canvas size in CSS pixels, then scale its backing store.
canvas.width = rect.width * dpr;
canvas.height = rect.height * dpr;
// Scale the context to ensure drawings are not stretched.
const ctx = canvas.getContext('2d');
ctx.scale(dpr, dpr);
// Now your drawings will be crisp.
ctx.fillRect(10, 10, 100, 100);
How to Choose: The Decision Framework
Your choice depends on the intersection of element count and interactivity needs. There is no single "better" option, only the right tool for the job.
Use this decision flow to structure your answer.
Start your interview answer by framing the problem this way. "First, I'd clarify the requirements. How many data points are we talking about? Do we need to interact with individual points, or just the chart as a whole? Is accessibility a primary concern?"
This shows you understand the core trade-offs before jumping to a solution. For a scatter plot with 50,000 points, say Canvas. For an interactive dashboard with 20 distinct, clickable charts, say SVG. For a hybrid, mention layering a transparent SVG for UI elements (like tooltips or selection boxes) over a Canvas for the dense data.
Show the Difference: Imperative vs. Declarative Code
The programming model is fundamentally different. SVG is declarative: you describe what you want, and the browser builds a DOM tree. Canvas is imperative: you give the browser step-by-step instructions on how to draw.
Here's how you'd draw 1,000 random circles with each.
SVG (Declarative): You generate an array of data, and your view layer (e.g., React, Svelte) maps it to SVG elements. The result is a large DOM fragment.
// Assuming a framework that renders this array into SVG
function createSvgCircles(count) {
const circles = [];
for (let i = 0; i < count; i++) {
circles.push({
cx: Math.random() * 300,
cy: Math.random() * 300,
r: 2,
fill: 'blue',
});
}
// In React: return circles.map(c => <circle {...c} />);
// In vanilla JS: return circles.map(c => `<circle cx="${c.cx}" ... />`).join('');
return circles;
}
Canvas (Imperative): You get a drawing context and issue a series of commands inside a loop. Nothing is added to the DOM.
function drawCanvasCircles(canvas, count) {
const ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, canvas.width, canvas.height); // Clear canvas
ctx.fillStyle = 'blue';
for (let i = 0; i < count; i++) {
const cx = Math.random() * canvas.width;
const cy = Math.random() * canvas.height;
ctx.beginPath();
ctx.arc(cx, cy, 2, 0, 2 * Math.PI);
ctx.fill();
}
}
The Canvas code is often more verbose but avoids the performance cost of DOM manipulation for every single shape.
Try it
Open a CodePen or local file. Render 5,000 small circles using both SVG and Canvas. Use requestAnimationFrame to slightly change their position on each frame. Observe the difference in frame rate using your browser's performance profiler.
Next: We'll build on this by making our visualizations interactive and responsive in the lesson on Interactive, Responsive Data Visualizations.
Lock it in — apply this lesson under interview conditions.