Skip to content

Instantly share code, notes, and snippets.

@jamestthompson3
Last active October 29, 2018 18:08
Show Gist options
  • Save jamestthompson3/637aa4707e0ecd54322e148bc367e21d to your computer and use it in GitHub Desktop.
Save jamestthompson3/637aa4707e0ecd54322e148bc367e21d to your computer and use it in GitHub Desktop.
React Voronoi
import * as React from "react"
import { voronoi } from "@vx/voronoi"
class Voronoi extends React.Component {
tile = null
componentDidMount() {
this.renderPoints()
}
renderPoints = () => {
if (!this.tile) return
const { data, yScale, xScale } = this.props
const context = this.tile.getContext("2d")
const voronoiDiagram = voronoi({
x: d => xScale(d.x),
y: d => yScale(d.y),
width: this.tile.width,
height: this.tile.height
})(data)
const polygons = voronoiDiagram.polygons()
const constructPath = polygon => `M${polygon.join("L")}Z`
context.strokeStyle = "#2cdea3"
context.strokeWidth = 2
polygons.forEach(polygon => {
const p = new Path2D(constructPath(polygon))
context.stroke(p)
context.fillStyle = "rgba(0, 157, 105, 0.3)"
context.fill(p)
})
}
render() {
const { width, height } = this.props
return (
<canvas ref={ref => (this.tile = ref)} width={width} height={height} />
)
}
}
export default Voronoi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment