Published
Edited
Feb 6, 2021
1 star
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
nodes = new Array(cols*cols).fill(0).map((d, i) => {
let col = i%cols
let row = Math.floor(i/cols)
return {
x: 10+col*300/cols + Math.random(),
y: 10+row*300/cols + Math.random()
}
})
Insert cell
check = i => {
let col = i%cols
let row = Math.floor(i/cols)
return (col%cellCols==0 || row%cellCols==0)
}
Insert cell
applyForceRepulsion = () => {
for (let i = 0; i < nodes.length; i++) {
if (check(i) == false) continue;
for (let j = i+1; j < nodes.length; j++) {
if (check(j) == false) continue;
if(i == j) continue;
let n1 = nodes[i]
let n2 = nodes[j]
let dx = n2.x - n1.x
let dy = n2.y - n1.y
if(dx==0 && dy==0) continue;
let a = Math.atan2(dy, dx)
let dist = Math.hypot(dx, dy)
let forceRepulsion = kRepulsion / dist**2
if (forceRepulsion > 1)
forceRepulsion = 1
n1.x -= forceRepulsion * Math.cos(a)
n1.y -= forceRepulsion * Math.sin(a)
n2.x += forceRepulsion * Math.cos(a)
n2.y += forceRepulsion * Math.sin(a)
}
}
}
Insert cell
applyForceSpring = () => {
for (let i = 0; i < edges.length; i++) {
if (check(edges[i][0]) == false) continue;
if (check(edges[i][1]) == false) continue;
let n1 = nodes[edges[i][0]]
let n2 = nodes[edges[i][1]]
let dx = n2.x - n1.x
let dy = n2.y - n1.y
let a = Math.atan2(dy, dx)
let dist = Math.hypot(dx, dy)
let forceSpring = kSpring * (-dist)
console.log(forceSpring)
n1.x -= forceSpring * Math.cos(a)
n1.y -= forceSpring * Math.sin(a)
n2.x += forceSpring * Math.cos(a)
n2.y += forceSpring * Math.sin(a)
}
}
Insert cell
cols = cellCols*2 + 1
Insert cell
cellCols = 20
Insert cell
edges = {
let edges = []
for (let i = 0; i < nodes.length; i++) {
let col = i%cols
let row = Math.floor(i/cols)
if ((col+1)%cols)
edges.push([i, i+1])
if ((row+1)%cols)
edges.push([i, i+cols])
}
return edges
}
Insert cell
Type JavaScript, then Shift-Enter. Ctrl-space for more options. Arrow ↑/↓ to switch modes.

Insert cell
Insert cell
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more