First Bar Chart — Pageviews by Page

This demo draws a complete bar chart on an HTML Canvas element using only the 2D context API. No charting library is involved. The sample data represents pageviews for five pages on a website — the kind of data your analytics pipeline would produce.

How to read this demo: The chart is drawn by the JavaScript below. Each step is commented so you can follow the data-to-pixel mapping process. Open the browser source (Ctrl+U / Cmd+Opt+U) and read the code alongside the chart.

Step 1 — Data and Layout

Define the sample data array and the margin convention that separates the chart area from the title and axis labels. Each data item has a page (category) and views (quantity).

Step 2 — HiDPI Setup

Detect devicePixelRatio and scale the canvas drawing surface so the chart looks crisp on Retina displays. After this step, all coordinates are in logical (CSS) pixels.

Step 3 — Scale Functions

Compute the maximum data value and define scaleY(value), which maps a pageview count to a y-pixel coordinate. Remember: larger values produce smaller y values because canvas y=0 is at the top.

Step 4 — Gridlines and Axes

Draw horizontal gridlines at evenly spaced value intervals, with numeric labels on the y-axis. Then draw the x-axis baseline.

Step 5 — Bars and Labels

Loop through the data array, compute each bar's x/y/width/height, fill the rectangle, and add the page name below and the view count above each bar.

Step 6 — Title and Annotation

Add a chart title centered at the top and a y-axis label to complete the chart.

← Back to Module 01 | Canvas Basics Playground