What is it, and why is it useful?
By now, after completing the previous modules, you’re likely able to draw almost anything on the screen— including interactive elements like tooltips, hover effects, and animations.
However, there's a significant bottleneck: performance. Let's explore canvas
, a rendering engine that can help solve this issue.
The Problem with SVG
SVG can be slow.
If you’re working with chart types that don’t involve too many elements, like simple line or bar charts, SVG will handle them well.
But if you create a scatterplot with 100,000 data points and layer on complex animations, you’ll likely run into performance troubles.
So, why is SVG slow?
🐢 Drawing SVG is CPU-Only
SVG rendering relies entirely on the CPU, with no GPU acceleration.
This means every shape, line, or point in an SVG graphic is drawn by the CPU, which can quickly become a bottleneck. Without the benefit of GPU power, rendering large amounts of data or intricate animations can be time-consuming and sluggish.
🏋️♀️ SVG Creates a Heavy DOM
Each element you draw in SVG is added as a separate line in the DOM.
For a large number of elements, this quickly bloats the DOM, which your browser has to continuously manage and render.
Adding event listeners to each element further increases the workload, as the browser must keep track of interactions on all these individual DOM nodes. And as the DOM grows, memory usage rises as well, which can lead to even more slowdowns.
Example
Here’s a small scatterplot with a few thousand data points and a hover effect that updates an internal state.
Hover over it with your mouse. Notice the lag? See how slow it gets?
With just a few graphs like this in your app, you can quickly reach a million nodes in the DOM 🙈.
When that happens, your entire app—or even the whole browser—can start to freeze as it struggles to manage the overwhelming number of elements.
So,
If your graph has a large number of elements or requires heavy animations, it’s best to move away from SVG and choose something more performant, like
canvas
.
⚡️ What is canvas, and why is it fast
Canvas provides a high-performance, low-level context for drawing 2D graphics, animations, and even simple games, giving you pixel-level control for faster rendering, especially with dynamic content or large datasets.
canvas
is an HTML element! You can create one by writing:
<canvas width={300} height={200}/>
Think of it like holding a whiteboard, ready to draw on it—only lightning fast!
Not convinced?
Check the same sandbox, made in Canvas!
A scatterplot with thousands of point and a fast hover effect.
Looks fun, let’s code!
Yep, but be ready to learn from scratch—and to break a sweat!
In this module, we’ll dive into how the canvas
works, how to use it effectively, and how it can solve performance issues in your web apps.