← Back to JavaScript Course | Chapter 10: DOM Advanced | Lesson 6 of 8

JS Graphics

HTML gives you elements to display text, images, and forms, but drawing arbitrary shapes, charts, or animations pixel-by-pixel needs a different tool entirely. JavaScript's graphics capabilities -- primarily the Canvas API, with libraries like Chart.js built on top of it -- let you paint directly onto a rectangular drawing surface embedded in the page.

What JavaScript Graphics Can Do

Beyond styling existing HTML elements, JavaScript graphics tools let you draw completely custom visuals -- charts, game sprites, data visualizations, generated patterns -- directly onto a drawing surface, pixel by pixel, under full programmatic control.

Note: Reach for graphics tools specifically when you need custom, dynamic, or data-driven visuals that plain HTML and CSS cannot easily produce.
Warning: Building complex custom graphics from scratch is significantly more work than styling HTML elements -- reserve it for visuals that genuinely need that level of control.

उदाहरण: What JavaScript Graphics Can Do

javascript
<canvas id="chart" width="200" height="100"></canvas>
<script>
  const ctx = document.getElementById("chart").getContext("2d");
  ctx.fillStyle = "blue";
  ctx.fillRect(10, 10, 50, 50); // pixel-level drawing, not just styled HTML
</script>

The Canvas Element as a Drawing Surface

A <canvas> element is essentially a blank rectangular area in the page with no visual content of its own -- it becomes useful only once JavaScript retrieves its drawing context and starts issuing drawing commands against it.

Note: Always set explicit width and height attributes on the canvas element itself, since CSS-only sizing can distort the coordinate system used for drawing.
Warning: A canvas with no JavaScript drawing to it renders as a completely blank, invisible rectangle -- easy to mistake for a bug when it is simply empty.

उदाहरण: The Canvas Element as a Drawing Surface

javascript
<canvas id="myCanvas" width="200" height="100"></canvas>
<script>
  const canvas = document.getElementById("myCanvas"); // blank until drawn on
  const ctx = canvas.getContext("2d");
  ctx.fillRect(20, 20, 100, 50);
</script>

Rendering Data Visually

Beyond static shapes, canvas is commonly used to render data-driven visuals -- bar charts built from an array of values, simple line graphs plotting trends over time -- computing pixel positions from the underlying data each time it changes.

Note: Separate your data (plain JavaScript values) from your drawing code, recalculating pixel positions from the data whenever it updates, rather than hardcoding pixel coordinates.
Warning: Manually computing chart coordinates and scaling for anything beyond a very simple visualization gets complex quickly -- this is exactly the kind of work a charting library exists to handle.

उदाहरण: Rendering Data Visually

javascript
<canvas id="chart" width="200" height="100"></canvas>
<script>
  // Declare the constant `data`, set to `[30, 80, 45, 60]`
  const data = [30, 80, 45, 60];
  // Declare the constant `ctx`, set to `document.getElementById("chart").getContext("2d")`
  const ctx = document.getElementById("chart").getContext("2d");
  // Call `data.forEach((value, i) => ctx.fillRect(i * 40, 100 - value, 30, value))`
  data.forEach((value, i) => ctx.fillRect(i * 40, 100 - value, 30, value));
</script>

Hand-Rolled Drawing vs Using a Library

Writing raw Canvas API calls for a simple shape or a one-off visualization is reasonable, but for common chart types (bar, line, pie, scatter) with axes, labels, legends, tooltips, and animations, a library like Chart.js handles an enormous amount of complexity you would otherwise have to build yourself.

Note: Prototype quickly with raw canvas for a very simple or highly custom visual; reach for Chart.js the moment you need standard chart features like axes, legends, or tooltips.
Warning: Reinventing standard charting features (axis labels, legends, responsive resizing) that a mature library already solves is a common source of wasted effort on custom dashboards.

उदाहरण: Hand-Rolled Drawing vs Using a Library

javascript
<canvas id="c1" width="100" height="100"></canvas>
<script>
  // Call `document.getElementById("c1").getContext("2d").fillRect(10, 10, 50, 50)`
  document.getElementById("c1").getContext("2d").fillRect(10, 10, 50, 50);
</script>
<!-- For real charts with axes/legends/tooltips, use a library like Chart.js instead -->

Choosing Between Canvas and Other Graphics Approaches

Canvas is best suited for pixel-based, frequently redrawn, or animated graphics (games, live data visualizations); SVG is often a better fit for graphics that need to stay resolution-independent and individually interactive, since SVG shapes remain real, selectable DOM elements unlike canvas pixels.

Note: Choose canvas for high-frequency redraws (animations, games) and SVG for graphics needing crisp scaling or individual shape interactivity.
Warning: A canvas-based graphic scales as a bitmap image would, becoming blurry when stretched larger, unlike SVG which remains sharp at any size.

उदाहरण: Choosing Between Canvas and Other Graphics Approaches

javascript
<canvas id="pixels" width="50" height="50"></canvas>
<svg width="50" height="50"><circle cx="25" cy="25" r="20" fill="green"/></svg>
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
🔒

Chapter Quiz — Complete all 8 topics to unlock

0/8 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.