Open in a new tab

A Canvas 2D line chart with round axes from zero, redrawn when a value is added, with a summary and a data table for anyone who cannot see the canvas.

Uses @awacloud/fw (Apache-2.0). This example's code is Apache-2.0.

When to use it

A small chart in an app or a status page: a trend over days, a metric over time. fw's chart draws line, area, bar and sparkline, with no tooltips, legends or pie charts; for those, use a charting library.

Copy-paste steps

  1. npm install @awacloud/fw
  2. Serve node_modules/@awacloud/fw/src/ at /vendor/fw/ (node serve.js from the examples root does this; any static server works).
  3. Copy index.html, main.js and style.css next to each other and open index.html through that server. The ../../_style/examples.css link is optional: copy that file along, or delete the link.

What it shows

  • chart.line({ el, data, color, xAxis, yAxis }) on a container: chart adds the canvas, scales it for high-density screens and redraws when the container resizes. style.css lets the canvas follow the container (chart sets its size in pixels).
  • Axes: chart's default ticks are round values (a step of 1, 2, 2.5 or 5 × 10ⁿ, at most four intervals), and its default domain is the data range plus 5 %. The page passes a domain from zero for both axes, a format for each (1000 ms, d3) and, on x, one tick every other day. The left margin grows to fit the widest y label.
  • handle.setOpts({ data, xAxis, yAxis }) redraws with new data and new axes; handle.update(data) would keep the old axes.
  • A canvas is one image to a screen reader: role="img" with an aria-label summary, and the full data as a table under "The data".
  • color must be a hex value (#4a9eff, not a CSS variable): for area and bar charts, chart appends an alpha to it for the fill.

Code

main.js

javascriptApache-2.050 lines

// SPDX-License-Identifier: Apache-2.0
import fw from '@awacloud/fw';
import { chart } from '@awacloud/fw/dom/rendering/chart.js';

fw.runtime.registerAllDeep([chart]);
const CHART = fw.runtime.resolve('chart');

/** @param {string} id */
const el = (id) => /** @type {HTMLElement} */ (document.getElementById(id));
/** Page load times in ms, one per day: the series the chart and the table both show. */
const loads = [820, 790, 845, 760, 910, 880, 700, 690, 720, 650, 640, 700, 610, 590];

/** Axes from zero (chart's default domain is the data range plus 5 %); one x tick per few days. */
function axes() {
    const top = Math.ceil(Math.max(...loads) / 250) * 250;
    const every = Math.max(1, Math.round((loads.length - 1) / 6));
    const days = loads.map((_, day) => day).filter((day) => day % every === 0);
    return {
        xAxis: { domain: [0, loads.length - 1], ticks: days, format: (/** @type {number} */ day) => `d${day + 1}` },
        yAxis: { domain: [0, top], format: (/** @type {number} */ ms) => `${ms} ms` }, // round default ticks
    };
}

// The container, not a canvas: chart adds the canvas and redraws when the container resizes.
// The colour must be hex: for area and bar charts, chart appends an alpha to it for the fill.
const handle = CHART.line({ el: el('chart'), data: loads, color: '#4a9eff', ...axes() });

/** A canvas is an image to assistive technology: give it a summary, and the full data as a table. */
function describe() {
    el('chart').setAttribute('aria-label',
        `Line chart of page load time over ${loads.length} days, from ${loads[0]} ms to ${loads.at(-1)} ms.`);
    el('rows').replaceChildren(...loads.map((ms, i) => {
        const row = document.createElement('tr');
        row.append(Object.assign(document.createElement('td'), { textContent: `Day ${i + 1}` }),
            Object.assign(document.createElement('td'), { textContent: `${ms} ms` }));
        return row;
    }));
}
describe();

// A new measurement: the same array feeds the chart and the table. setOpts, not update(): the axes change too.
el('add').addEventListener('submit', (event) => {
    event.preventDefault();
    const input = /** @type {HTMLInputElement} */ (el('ms'));
    if (!input.checkValidity()) return;
    loads.push(input.valueAsNumber);
    handle.setOpts({ data: loads, ...axes() });
    describe();
    input.value = '';
});

index.html

htmlApache-2.035 lines

<!doctype html>
<!-- SPDX-License-Identifier: Apache-2.0 -->
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>fw · Chart a series, with its table</title>
  <link rel="stylesheet" href="../../_style/examples.css">
  <link rel="stylesheet" href="./style.css">
  <script type="importmap">
  { "imports": {
    "@awacloud/fw": "/vendor/fw/main.js", "@awacloud/fw/": "/vendor/fw/" } }
  </script>
  <script type="module" src="./main.js"></script>
</head>
<body>
  <main>
    <h1>Chart a series, with its table</h1>
    <p id="caption">Page load time per day, in milliseconds</p>
    <div id="chart" class="chart" role="img"></div>
    <form id="add">
      <label for="ms">Today's load time (ms)</label>
      <input id="ms" type="number" min="1" max="10000" required>
      <button type="submit">Add</button>
    </form>
    <details>
      <summary>The data</summary>
      <table>
        <thead><tr><th scope="col">Day</th><th scope="col">Load time</th></tr></thead>
        <tbody id="rows"></tbody>
      </table>
    </details>
  </main>
</body>
</html>

style.css

cssApache-2.04 lines

/* SPDX-License-Identifier: Apache-2.0 */
.chart { height: 16rem; margin-block: 1rem; }
/* chart sets the canvas size in px; !important lets it follow the container when the page resizes. */
.chart canvas { display: block; width: 100% !important; height: 100% !important; }