Docs · Tutorial

Measure between two points

A web page that draws a block with a bore through it, snaps the cursor to its corners, edge midpoints and the bore's centre, and measures the distance between two clicked points, drawing the segment and its length on the part. It builds on A web view in ten lines: the same two files, and about sixty lines of JavaScript. Every file below is shown whole, and each one was run as it is.

Step 1

What you need

The web package's pkg/ folder and a static file server, as in A web view in ten lines, which this page builds on: the reader (it carries the license), the kernel (the block and its bore) and the viewer (View and view.js). Make a folder with the page's files beside pkg/:

measure/
├── pkg/            the web package's pkg/: reader + kernel + viewer
├── cadaclysm.lic   your license, if you have one
├── index.html      the page: one canvas and a status line
└── main.js         the part, the snapping and the two clicks
Step 2

The page

index.html: one canvas that fills the window, and a status line over its corner that says what is under the cursor and, at the end, the measurement.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Measure between two points</title>
  <style>
    html, body { margin: 0; height: 100%; background: #15171a; }
    canvas { display: block; width: 100%; height: 100%; }
    #status { position: fixed; left: 12px; bottom: 8px; margin: 0; color: #ddd; font: 13px/1.4 ui-monospace, monospace; }
  </style>
</head>
<body>
  <canvas id="view"></canvas>
  <p id="status">hover the part; click two points</p>
  <script type="module" src="main.js"></script>
</body>
</html>
Step 3

The part, and snapping on

main.js, the whole of it:

import { load, View, cadaclysm_blacksmith_cuboid, cadaclysm_blacksmith_cylinder,
         cadaclysm_blacksmith_translate, cadaclysm_blacksmith_cut, cadaclysm_blacksmith_solid_free } from "./pkg/index.js";
import { attachControls } from "./pkg/view.js";

await load({ license: "./cadaclysm.lic" });

const canvas = document.getElementById("view");
const status = document.getElementById("status");
const viewer = await View.create(canvas, { surfaces: "exact" });

// A block with a bore through it: corners, edge midpoints and a circle's centre to snap to.
const box = cadaclysm_blacksmith_cuboid(60, 40, 20);
const bar = cadaclysm_blacksmith_cylinder(8, 40);
const moved = cadaclysm_blacksmith_translate(bar, 0, 0, -20);
const part = cadaclysm_blacksmith_cut(box, moved, 0.05);
viewer.showSolid(part);
for (const h of [box, bar, moved, part]) cadaclysm_blacksmith_solid_free(h);

viewer.setSnap({ kinds: ["vertex", "midpoint", "centre", "quadrant", "edge"] });
attachControls(canvas, viewer);
viewer.start();

// The cursor in device pixels, as snap takes them.
function pixel(e) {
  const r = canvas.getBoundingClientRect();
  return [(e.clientX - r.left) * devicePixelRatio, (e.clientY - r.top) * devicePixelRatio];
}
const show = (p) => p.map((c) => c.toFixed(2)).join(", ");

// One snap in flight. A snap answers a frame or two later; a move that comes meanwhile
// only records where the pointer is, and is asked when the answer lands -- so the marker
// follows the pointer and no answer older than it is kept.
let asking = false;
let wanted = null;   // the newest pointer position not asked yet
let under = null;    // the newest answer: what a click measures to

function ask(at) {
  asking = true;
  viewer.snap(0, at[0], at[1]).then((snap) => {
    asking = false;
    if (wanted) {
      const next = wanted;
      wanted = null;
      ask(next);
      return;
    }
    under = snap;
    if (snap) {
      const here = `${snap.kind} at ${show(snap.point)}`;
      status.textContent = from === null ? here : `A ${show(from)}: ${here}`;
    }
  });
}

canvas.addEventListener("pointermove", (e) => {
  if (e.buttons !== 0) return;   // a drag orbits; it does not snap
  if (asking) wanted = pixel(e);
  else ask(pixel(e));
});

// Two clicks measure: the first sets A, the second B, and the View draws the segment
// with its length at its middle. A click ends a drag too, so one that moved is not a click.
let from = null;
let drawn = [];
let down = null;
canvas.addEventListener("pointerdown", (e) => { down = [e.clientX, e.clientY]; });
canvas.addEventListener("click", (e) => {
  if (!down || Math.hypot(e.clientX - down[0], e.clientY - down[1]) > 4 || !under) return;
  if (from === null) {
    for (const id of drawn) viewer.remove(id);
    drawn = [];
    from = under.point;
    status.textContent = `A ${show(from)}: click the second point`;
    return;
  }
  const to = under.point;
  const length = Math.hypot(to[0] - from[0], to[1] - from[1], to[2] - from[2]);
  const middle = from.map((c, i) => (c + to[i]) / 2);
  drawn = [
    viewer.showLines([...from, ...to], [1.0, 0.8, 0.2]),
    viewer.showText(`${length.toFixed(2)} mm`, { at: middle, box: [0, 0, 0, 0.6], padding: 4, onTop: true }),
  ];
  status.textContent = `${length.toFixed(2)} mm from A ${show(from)} to B ${show(to)}`;
  from = null;
});
Step 4

One snap in flight

A snap is asked of the GPU, and its answer comes a frame or two later. Pointer moves arrive faster than that, and the answers are not ordered for you: if every move asked, an answer to an old position could land last and put the marker, and the status line, behind the pointer. So ask keeps one snap out. A move that comes meanwhile only records where the pointer is in wanted, and is asked when the answer lands, with the answer to the position it replaces dropped. under is always the answer to the newest position asked, which is what a click measures to. A move with a button down is a drag, which orbits, so it does not snap.

Step 5

Two clicks

The first click keeps the snapped point as A, and clears what the last measurement drew. The second takes B, works out the distance in all three coordinates and draws it: showLines draws the segment, and showText a label at its middle, on a dark box, onTop so that a part in front does not hide it. Both return ids, which the next measurement hands to remove. A drag ends in a click too, so a click that moved more than 4 pixels since the pointer went down is skipped.

Step 6

Run it

Serve the folder, as before:

cd measure
python -m http.server 8000

Open http://localhost:8000/. Move over the block: a marker follows the cursor to the nearest corner, edge midpoint or bore point, and the status line names it. Click two of them: a yellow segment joins them, with its length on the part. This is it, running: the files above, served beside this site's own module (open it on its own):

Step 7

Change it

A line each, in main.js after the View is made. Every kind (omitting kinds means all of them):

viewer.setSnap({});

A wider aperture, in points:

viewer.setSnap({ aperturePx: 20 });

The page's own marker: the View keeps its marker off, and the page draws one from the answer's point.

viewer.setSnap({ marker: false });

Snaps on a plane of your own, in place of the grid's: with "grid" among the kinds, the cursor lands on the plane's grid points, here 5 mm apart on the plane at z = 10, the block's top. setWorkPlane(null) puts the grid's own back.

viewer.setSnap({ kinds: ["vertex", "grid"] });
viewer.setWorkPlane({ origin: [0, 0, 10], xAxis: [1, 0, 0], normal: [0, 0, 1], step: 5 });

A View in a worker, as in step 6 of the first tutorial: the page asks the worker with client.snap(x, y), which resolves as viewer.snap does, and turns snapping on through client.view.setSnap(...) (see In a web page).

Next

Where next

In a web page is the reference: every method of the View, the kernel and the license. A web view in ten lines is the page this one grew from.

← A web view in ten lines · All languages