You will be able to choose between Canvas, SVG, and chart libraries, and draw a simple data visualization in the browser using JavaScript.
What it is
JavaScript graphics means creating visual output in the browser. The main approaches are Canvas, SVG, and chart libraries. Canvas is a bitmap drawing surface controlled through a JavaScript drawing context. SVG is XML-based vector graphics inserted into the DOM. Chart libraries, such as Chart.js or D3, provide higher-level APIs for common visualizations.
A useful mental model is: Canvas is like painting on paper, while SVG is like arranging objects in a document. Related terms include 2D context, path, fill, stroke, viewBox, and DOM.
Why it matters
- Build dashboards, charts, and data visualizations without server-side rendering.
- Create interactive graphics for games, diagrams, maps, and annotations.
- Respond to user input by redrawing or updating visual elements.
- Choose the right technology for performance, accessibility, and maintainability.
Syntax or steps
The smallest useful Canvas pattern is:
- Create or select a
canvaselement. - Get its drawing context with
getContext('2d'). - Clear the canvas with
clearRect(). - Set drawing styles such as
fillStyle. - Draw shapes using methods like
fillRect(),beginPath(),moveTo(),lineTo(),stroke(), orfill().
For SVG, you usually create elements with document.createElementNS() and append them to an svg element.
Example
<canvas id="chart" width="400" height="200"></canvas>
<script>
const canvas = document.getElementById('chart');
const ctx = canvas.getContext('2d');
const data = [30, 80, 50, 100];
function drawBars(values) {
if (values.length === 0) return;
ctx.clearRect(0, 0, canvas.width, canvas.height);
const maxValue = Math.max(...values);
const slotWidth = canvas.width / values.length;
const barWidth = slotWidth * 0.7;
const gap = slotWidth * 0.3;
ctx.fillStyle = '#4f46e5';
for (let i = 0; i < values.length; i++) {
const height = (values[i] / maxValue) * canvas.height;
const x = i * slotWidth + gap / 2;
const y = canvas.height - height;
ctx.fillRect(x, y, barWidth, height);
}
}
drawBars(data);
</script>
Part-by-part explanation
The canvas element defines a pixel surface. getContext('2d') returns the drawing API. clearRect() removes previous drawing. Math.max() finds the largest value so bars can be scaled proportionally. The loop calculates each bar’s position and height, then fillRect() draws it.
Common mistakes
- Forgetting to clear the canvas before redrawing, causing old graphics to remain.
- Setting only CSS width and height, which stretches the bitmap; set
canvas.widthandcanvas.heightfor real pixel size. - Using Canvas for simple static charts when SVG or a chart library would be easier and more accessible.
- Not handling empty data, which can cause
Math.max()to return-Infinity.
When to use it
| Approach | Best for | Watch out |
|---|---|---|
| Canvas | Games, many shapes, pixel-level drawing, high-frequency updates | Less accessible; you manage redraws yourself |
| SVG | Icons, diagrams, charts with selectable elements, responsive vector graphics | Can slow down with very large numbers of elements |
| Chart library | Standard charts, tooltips, legends, quick dashboards | Less control and extra dependency |
Practice
- Guided exercise: modify the example so each bar has a different color. Expected output: four bars with distinct colors.
- Challenge: add value labels above each bar. Hint: use
ctx.fillText(), setctx.font, and calculate the label position fromx,y, andbarWidth.
Quick check
Question: When is Canvas usually a better choice than SVG?
Answer: When you need to draw many shapes quickly, animate frequently, or control pixels directly, such as in games or large interactive visualizations.
Summary
JavaScript graphics lets you turn data and interaction into visual browser output. Canvas gives low-level control, SVG gives structured vector elements, and chart libraries give fast, reusable visualizations.