Updating a chart

For most charts, use <t-vega>, which draws a Vega-Lite spec, or <t-obsplot>, which draws an Observable Plot chart. Neither needs a script. For any other chart, a few lines of JavaScript do it: the variables stay in the HTML, and a script reads them and draws.

A live chart

Throw a ball at 22, 30 above the ground. It reaches high and lands away.

Drag the speed or the angle in the text, or drag the chart: pull the top of the arc anywhere to set both, or slide the landing point along the ground to throw further at the same angle.

How it works

  1. The HTML declares the variables. The two <t-num> elements and three <t-let> values live in <t-scope id="throw">, which keeps them apart from the other examples on the page. The <svg> holds empty shapes for the script to position. The script declares no variables of its own.
  2. scopeOf(root) gets the scope that holds those variables. root is the <t-scope>, found by its id, but any element inside it works. On a page without a <t-scope>, use scopeOf(document). See A first script.
  3. The scales are fixed. x and y turn metres into pixels, and they never change. If the chart rescaled to fit each throw, a 20 m throw would look the same as an 80 m one, and dragging would only change the numbers.
  4. Parts that never change are drawn once. The gridlines and labels are built before the effect, so they're not rebuilt on every change.
  5. effect(fn) draws the parts that change. It runs fn once straight away, and remembers each variable that s.get read: speed, rad, range and peak. When any of those changes, it runs again and moves the existing shapes.
  6. Changes are batched. Dragging the angle changes rad, range and peak too, but the effect runs once per change.

The effect reads computed variables too. range and peak come from the <t-let> elements, so the text and the chart can't disagree.

The colors come from CSS, using currentColor and var(--tangle-accent), so the chart follows the theme (light or dark) with no extra code.

Drawing on a canvas

A canvas needs explicit colors and pixel sizes. Read the colors from CSS when you draw, and redraw when the canvas changes size. A redraw for some other reason, like a resize, should use peek, so it doesn't subscribe to anything:

import { scopeOf } from "/tangle.js";

const canvas = document.querySelector("#plot");
const scope = scopeOf(canvas);
const css = (name) => getComputedStyle(canvas).getPropertyValue(name).trim();

function draw(a, b) {
  const { width, height } = canvas.getBoundingClientRect();
  canvas.width = width * devicePixelRatio;
  canvas.height = height * devicePixelRatio;
  const g = canvas.getContext("2d");
  g.scale(devicePixelRatio, devicePixelRatio);
  g.strokeStyle = css("--tangle-accent");
  // ...
}

scope.effect((s) => draw(s.get("a"), s.get("b")));
new ResizeObserver(() => draw(scope.peek("a"), scope.peek("b"))).observe(canvas);

The parabola on the home page is drawn this way.

Using a chart library

With a library, create the chart once outside the effect. Then, in the effect, give it new data and ask it to update. Turn animations off, so the chart follows a drag instead of lagging behind it. With Chart.js:

const chart = new Chart(canvas, { type: "line", data: { labels: [], datasets: [{ data: [] }] } });

scopeOf(canvas).effect((s) => {
  const years = Array.from({ length: s.get("years") + 1 }, (_, i) => i);
  chart.data.labels = years;
  chart.data.datasets[0].data = years.map((t) => s.get("start") * (1 + s.get("rate") / 100) ** t);
  chart.update("none"); // "none" skips the animation
});

Other libraries work the same way: with Plotly, call Plotly.react(el, data, layout) in the effect. With D3, run the update part of your join.

Letting the chart change variables

The data can flow the other way too. Dragging the chart calls scope.set, and every <t-num>, output and formula that uses speed or angle updates, including the chart itself.

Work out which variables a gesture should change from what the reader is pointing at. A reader who drags the top of the arc expects the arc's top to follow the pointer, so the handler solves the physics backwards for the speed and angle that put it there:

const toMetres = (event) => {
  // Convert the pointer from screen pixels to the SVG's own coordinates, then to metres.
  const p = new DOMPoint(event.clientX, event.clientY).matrixTransform(svg.getScreenCTM().inverse());
  return { d: (p.x - x(0)) / 5.4, h: (y(0) - p.y) / 5.4 };
};

// The top of the arc is at (d, h) when tan(angle) = 2h / d and speed² = 2gh / sin²(angle).
function aimPeak({ d, h }) {
  const a = Math.atan2(2 * h, d);
  scope.set("angle", clamp((a * 180) / Math.PI, 5, 85));
  scope.set("speed", clamp(Math.sqrt((2 * 9.81 * h) / Math.sin(a) ** 2), 5, 30));
}

set doesn't apply the variable's min, max or step, so clamp rounds and clamps the value itself. Near the edges the arc's top then stops short of the pointer instead of jumping around.

Use pointer events with setPointerCapture, so the drag keeps going when the pointer leaves the chart, and touch-action: none in the CSS, so a drag on a phone doesn't scroll the page.

effect returns a function that stops it. Call it if you remove the chart from the page.