Last active
October 29, 2018 18:08
-
-
Save jamestthompson3/637aa4707e0ecd54322e148bc367e21d to your computer and use it in GitHub Desktop.
React Voronoi
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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