Geometry

Clip a polyline to a rectangle

Find where a curve enters and leaves a rectangle, highlight the part inside and get it as a range along the curve. TypeScript with VisQuill.

/**
 * Demonstrates how to find the parts of a polyline that run through a
 * rectangular region.
 *
 * A draggable box defines the window. Polylines.clipToBox returns every part
 * of the polyline inside the box as a [from, to] range of ratios along it.
 * Each range drives Polylines.slice to highlight that part in a contrasting
 * colour; dots mark where the line enters and leaves the box.
 *
 * This is the foundation of the focused-route technique used in map
 * visualisations: when the box is the viewport frame and the polyline is a
 * reprojected route, the ranges tell you which parts of the route are
 * currently visible.
 */

import {
    VisQuill, Reactive, Boxes, Points, Segments, Polylines,
} from "@visquill/visquill-gdk";
import "./styles.css";

// ── Layout ────────────────────────────────────────────────────────────────────

const POLYLINE_POINTS: [number, number][] = [
    [  60, 340], [120, 180], [190, 400], [270, 130],
    [350, 300], [420,  90], [510, 360], [590, 160],
    [670, 320], [750, 110], [830, 280], [900, 380],
];

const SMOOTHING = 3;

const WINDOW_TL: [number, number] = [220, 200];
const WINDOW_BR: [number, number] = [760, 320];

// The line can cross the window many times; one highlight per part.
const MAX_PARTS = 12;

export function run(div: HTMLDivElement) {
    const rvg    = VisQuill.create(div, "demos-polyline-windowing-");
    const canvas = rvg.canvas;

    // ── Instructions ──────────────────────────────────────────────────────────

    const instructions = canvas.text.label(
        "Drag the window corners — every part inside is highlighted",
        "instructions"
    );
    Reactive.do([rvg.frame], () => {
        Points.moveDown(Segments.midPoint(Boxes.topSide(rvg.frame)), 25, instructions);
    });

    // ── Polyline ──────────────────────────────────────────────────────────────

    const polyline = Polylines.smooth(POLYLINE_POINTS, SMOOTHING);

    // The whole line dimmed, the parts inside the window on top of it
    Polylines.copy(polyline, canvas.visuals.polyline("line"));
    const parts = Array.from({ length: MAX_PARTS }, () =>
        canvas.visuals.polyline("part"));

    // ── Draggable window ──────────────────────────────────────────────────────
    //
    // Two corner handles define the window box via Boxes.spannedBox.
    // Either corner can be dragged past the other without breaking the box.

    const hTL = canvas.handles.disk("window-handle", WINDOW_TL);
    const hBR = canvas.handles.disk("window-handle", WINDOW_BR);

    const windowBox = canvas.visuals.box("window-rect");

    Reactive.do([hTL, hBR], () => {
        Boxes.spannedBox(hTL, hBR, windowBox);
    });

    // ── Entry / exit markers ──────────────────────────────────────────────────

    const entryDots = parts.map(() => canvas.visuals.point("entry-dot"));
    const exitDots  = parts.map(() => canvas.visuals.point("exit-dot"));

    // ── Range label ───────────────────────────────────────────────────────────

    const rangeLabel = canvas.text.label("", "range-label");
    Reactive.do([rvg.frame], () => {
        const bl = Boxes.bottomLeft(rvg.frame);
        Points.move(bl, 20, -30, rangeLabel);
    });

    // ── Reactive windowing ────────────────────────────────────────────────────
    //
    // Every time the window box changes, clip the polyline again. The ranges
    // are ascending; a part that touches the box only at one point is left out.

    const ranges: [number, number][] = [];

    Reactive.do([windowBox], () => {
        Polylines.clipToBox(polyline, windowBox, ranges);

        parts.forEach((part, i) => {
            const shown = i < ranges.length;
            part.visible.value         = shown;
            entryDots[i].visible.value = shown;
            exitDots[i].visible.value  = shown;
            if (!shown) return;

            const [from, to] = ranges[i];
            Polylines.slice(polyline, from, to, part);
            Polylines.pointAt(polyline, from, entryDots[i]);
            Polylines.pointAt(polyline, to,   exitDots[i]);
        });

        const pct = (v: number) => `${Math.round(v * 100)}%`;
        rangeLabel.value = ranges.length === 0
            ? "no part inside"
            : `${ranges.length} part${ranges.length > 1 ? "s" : ""}: `
              + ranges.map(([from, to]) => `${pct(from)} → ${pct(to)}`).join(", ");
    });
}

The part of a curve inside a draggable box, found as a range of ratios along it. The demo finds the crossings with Boxes.containsPoint and Polylines.closestPosition and cuts the curve with Polylines.slice.

How it works

Polylines.clipToBox returns every part of the polyline inside the box as a [from, to] range, in order along the line. A line that leaves the box and comes back gives one range per part. Passing an array as the last argument fills it in place:

Polylines.clipToBox(polyline, windowBox, ranges);

Each range drives one highlighted slice, and the entry and exit dots sit at its two ratios:

const [from, to] = ranges[i];
Polylines.slice(polyline, from, to, part);
Polylines.pointAt(polyline, from, entryDots[i]);
Polylines.pointAt(polyline, to,   exitDots[i]);

The slices come from a fixed pool of visuals; parts beyond the number of ranges are hidden.

API

  • Polylines.clipToBox: the parts of a polyline inside a box, as ratio ranges
  • Polylines.slice: the part between two ratios
  • Polylines.pointAt: the point at a ratio
  • Boxes.spannedBox: the window from its two corner handles

Notes

A part that touches the box only at one point is left out.

See also

  • geometry/polylines-03-slicing
  • geometry/polylines-09-convex-hull

API used

Also used (15)