Public
Edited
Nov 10, 2021
7 stars
Insert cell
Insert cell
Insert cell
Insert cell
{
// MAIN
const svg = d3.select(DOM.svg(width, 400))
.attr('style', 'border: 1px solid #eee')
const polygonLayer = svg.append('g')
.attr('class', 'polygon_layer')
const intersectLayer = svg.append('g')
.attr('class', 'intersect_layer')
const handlesLayer = svg.append('g')
.attr('class', 'circles_layer')
// set data for layers
const handles = handlesLayer.selectAll('g').data(_.flatten(mutable polygonPositions))
const polygons = polygonLayer.selectAll('g').data(mutable polygonPositions)

const clippedLayer = intersectLayer.append('path')
function update() {
handles.enter().selectAll('circle')
.attr('cx', (d) => d[0])
.attr('cy', (d) => d[1])

polygons.enter().selectAll('path')
.attr('d', d => {
return `${makeLine(d)}z`
})
switch (clippingMethod) {
case "union":
const unionPoints = clipping.union(
[mutable polygonPositions[0]],
[mutable polygonPositions[1]]
)
clippedLayer.attr('d', `${makeLine(_.flatten(_.flatten(unionPoints)))}z`)
.attr('class', 'union')
break;

case "intersection":
const polys = [
[mutable polygonPositions[0]],
[mutable polygonPositions[1]]
]
const intersectionPoints = clipping.intersection(...polys)
clippedLayer.attr('d', `${makeLine(_.flatten(_.flatten(intersectionPoints)))}z`)
.attr('class', 'intersection')
break;
case "xor":
const xorPoints = clipping.xor(
[mutable polygonPositions[0]],
[mutable polygonPositions[1]]
)
clippedLayer.attr('d', `${makeLine(_.flatten(_.flatten(xorPoints)))}z`)
.attr('class', 'xor')
break;
case "difference":
const differencePoints = clipping.difference(
[mutable polygonPositions[0]],
[mutable polygonPositions[1]]
)
clippedLayer.attr('d', `${makeLine(_.flatten(_.flatten(differencePoints)))}z`)
.attr('class', 'difference')
break;
default:
break;
}
}
// create polygons
polygons.enter().append('g')
.append('path')
.attr('class', 'edge')
.attr('stroke-width', 1.5)
.attr('stroke', '#eee')
.attr('fill', 'none')
// create circles
handles.enter().append('circle')
.attr("cursor", "move")
.attr("pointer-events", "all")
.attr('fill', 'salmon')
.attr('r', 8)
.call(d3.drag()
.on("drag", dragged))
update()
function dragged(point) {
point[0] = d3.event.x
point[1] = d3.event.y
mutable polygonPositions = mutable polygonPositions

update()
}
return svg.node()
}
Insert cell
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