Published
Edited
May 3, 2020
2 forks
6 stars
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
seed = Date.now()
Insert cell
noiseScale = 4500
Insert cell
n = 1000
Insert cell
svg`<svg width="${w}" height="${h}">
<rect width="${w}" height="${h}" stroke="blue" fill="none" />

<g>
${(() => {
const m = 36
const segments = array(m).map(i => PVector(w/2 + Math.cos(TAU / m * i) * h / 2, h/2 + Math.sin(TAU / m * i) * h / 2)).map((d, i, arr) => new Segment(d, arr[(i + 1) % arr.length]))
array(n).forEach(i => {
const pos = PVector(w/2, h/2).add(PVector.random2D().setMag(random(h / 2 - 5)))

// const angle = random(Math.PI)
// const angle = randInt(2) * Math.PI / 2
// const angle = randInt(4) * Math.PI / 4
const angle = random() < .8 ? randInt(4) * Math.PI / 4 : random(Math.PI)
// const angle = sn.noise3D(pos.x / noiseScale, pos.y /noiseScale, seed) * TAU
const dir = PVector.fromAngle(angle).setMag(h+w)

const segment = new Segment(pos.clone().add(dir), pos.clone().sub(dir))

const intersections = []
for (const s of segments) {
const intersection = segSegIntersection(segment, s)
if (intersection !== null) intersections.push(intersection)
}

if(intersections.length > 0) {
intersections.sort((a, b) => a.distSq(segment.center) > b.distSq(segment.center) ? 1 : -1)
const nearest = getNearestIntersections(segment, intersections)
if(nearest !== null) segments.push(new Segment(nearest[0], nearest[1]))
}
})

return segments.map((s, i) => i < m ? '' : `<line
stroke="black"
x1="${s.a.x}" y1="${s.a.y}"
x2="${s.b.x}" y2="${s.b.y}"
/>
`).join('\n')
})()}
</g>
</svg>`
Insert cell
mutable log = undefined
Insert cell
getNearestIntersections = (seg, intersections) => {
if(intersections.length === 2) return intersections
const closest = intersections[0]
const dir = seg.center.clone().sub(closest).invert().norm()
const second = intersections.find(d => PVector.sub(seg.center, d).norm().isEqualTo(dir, 0.01))

if(second) return [closest, second]
return null
}
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
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