Back to JavaScript Notes
Topic #430

JavaScript Graphics

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:

  1. Create or select a canvas element.
  2. Get its drawing context with getContext('2d').
  3. Clear the canvas with clearRect().
  4. Set drawing styles such as fillStyle.
  5. Draw shapes using methods like fillRect(), beginPath(), moveTo(), lineTo(), stroke(), or fill().

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.width and canvas.height for 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

  1. Guided exercise: modify the example so each bar has a different color. Expected output: four bars with distinct colors.
  2. Challenge: add value labels above each bar. Hint: use ctx.fillText(), set ctx.font, and calculate the label position from x, y, and barWidth.

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.

Want to go beyond the notes?

Join Coding Now Tech Institute's JavaScript course — live mentorship, real projects, and 100% placement support.

Enroll Now — Free Demo Available

JavaScript Graphics – FAQs

Quick answers about learning JavaScript Graphics in JavaScript.

This free note from Coding Now Tech Institute explains JavaScript Graphics in JavaScript — concept, syntax and worked code examples you can copy, run and revise before interviews.
Yes. Every JavaScript topic on Coding Now Tech Institute, including JavaScript Graphics, is 100% free with no signup required.
With focused practice, most students grasp JavaScript Graphics in 1–3 days from these notes; pairing it with Coding Now Tech Institute's mentor-led course takes you to job-ready depth faster.
Use the code examples in this note, then ask doubts for free on the Coding Now Tech Institute Community (/community) — expert instructors answer within 24 hours.
Call NowEnroll Now