Skip to content

Instantly share code, notes, and snippets.

@zakjan
Last active March 13, 2020 07:23
Show Gist options
  • Save zakjan/b370057873fec41a5d4449d12c3e46e6 to your computer and use it in GitHub Desktop.
Save zakjan/b370057873fec41a5d4449d12c3e46e6 to your computer and use it in GitHub Desktop.
d3-force WebWorker layout
function runLayout(graph) {
return new Promise(resolve => {
const workerCode = `
importScripts('https://unpkg.com/d3@5.14.2/dist/d3.min.js');
function runLayout(graph) {
const { nodes, links } = graph;
d3.forceSimulation(nodes)
.force('link', d3.forceLink(links).id(d => d.id))
.force('charge', d3.forceManyBody().strength(-250))
.force('center', d3.forceCenter())
.stop()
.tick(300);
const positions = Object.fromEntries(nodes.map(node => {
return [node.id, { x: node.x, y: node.y }];
}));
return positions;
}
self.onmessage = event => {
const graph = event.data;
const result = runLayout(graph);
self.postMessage(result);
}
`;
const workerBlob = new Blob([workerCode], {
type: 'application/javascript'
});
const workerUrl = URL.createObjectURL(workerBlob)
const worker = new Worker(workerUrl);
worker.onmessage = event => {
resolve(event.data);
worker.terminate();
URL.revokeObjectURL(workerUrl);
};
worker.postMessage(graph);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment