Published
Edited
Dec 4, 2019
1 fork
Importers
38 stars
Insert cell
Insert cell
Insert cell
chart = {
const context = DOM.context2d(width, height);
const set = new Uint8Array(delaunay.points.length / 2);
const heap = new FlatQueue();
const tree = [];

function renderEdges(edges) {
for (const [i, j] of edges) {
context.moveTo(points[i * 2], points[i * 2 + 1]);
context.lineTo(points[j * 2], points[j * 2 + 1]);
}
}

function render() {
context.clearRect(0, 0, width, height);
context.beginPath(), renderEdges(heap.ids), context.strokeStyle = "#ccc", context.stroke();
context.beginPath(), renderEdges(tree), context.strokeStyle = "#f00", context.stroke();
context.beginPath(), delaunay.renderPoints(context), context.fill();
return context.canvas;
}

// Initialize the heap with the outgoing edges of vertex zero.
set[0] = 1;
for (const i of delaunay.neighbors(0)) {
heap.push([0, i], distance2(0, i));
}

// For each remaining minimum edge in the heap…
let edge;
while (edge = heap.pop()) {
const [i, j] = edge;
yield render();

// If j is already connected, skip; otherwise add the new edge to point j.
if (set[j]) continue;
set[j] = 1;
tree.push(edge);

// Add each unconnected neighbor k of point j to the heap.
for (const k of delaunay.neighbors(j)) {
if (set[k]) continue;
heap.push([j, k], distance2(j, k));
}
}

yield render();
replay;
}
Insert cell
function distance2(i, j) {
const dx = points[i * 2] - points[j * 2];
const dy = points[i * 2 + 1] - points[j * 2 + 1];
return dx * dx + dy * dy;
}
Insert cell
points = Float64Array.from({length: 600 * 2}, (_, i) => Math.random() * (i & 1 ? height : width))
Insert cell
delaunay = new d3.Delaunay(points)
Insert cell
height = 600
Insert cell
FlatQueue = require("flatqueue@1")
Insert cell
d3 = require("d3-delaunay@5")
Insert cell

One platform to build and deploy the best data apps

Experiment and prototype by building visualizations in live JavaScript notebooks. Collaborate with your team and decide which concepts to build out.
Use Observable Framework to build data apps locally. Use data loaders to build in any language or library, including Python, SQL, and R.
Seamlessly deploy to Observable. Test before you ship, use automatic deploy-on-commit, and ensure your projects are always up-to-date.
Learn more