block by dribnet 4760896

strokes: voronoi clipping

Full Screen

Looking for a small and easy to follow strokes example? You’ve found it.

A fork and port of mike’s js version (gist/block), for the strokes examples repo.

(merge requests should go to the example in the repo).


The Voronoi layout, d3.geom.voronoi, does not provide clipping by default; the returned diagram spans ±1e6. This example demonstrates how to clip the diagram to known dimensions.

index.html

<!DOCTYPE html>
<meta charset="utf-8">
<title>voronoi-clipping</title>
<style>

circle,
path {
  stroke: #000;
}

path {
  fill-opacity: .1;
}

path:hover {
  fill-opacity: .2;
}

</style>

<body>
  <script type="text/javascript" src="//d3js.org/d3.v3.min.js"></script>
	<script type="text/javascript" src="voronoi-clipping.js"></script>
</body>

voronoi-clipping.cljs

(ns voronoi-example
  (:require [clojure.string :refer [join]]
            [strokes :refer [d3 voronoi polygon category10]]))

(strokes/bootstrap)

(def padding 10)
(def width 960)
(def height 500)

(def points [[200 200]
             [760 300]])

(def vor-obj (-> (voronoi) (.clipExtent [
                [padding, padding]
                [(- width padding), (- height padding)]
              ])))

(def colorfn (category10))

(def svg (-> d3 (.select "body") (.append "svg")
      (.attr {:width width :height height})))

(-> svg (.selectAll "path")
      (.data (vor-obj points))
    (.enter)
      (.append "path")
      (.style "fill" #(colorfn %2))
      (.attr "d" #(str "M" (join "L" %) "Z")))

(-> svg (.selectAll "circle")
      (.data points)
    (.enter)
      (.append "circle")
      (.style "fill" #(colorfn %2))
      (.attr {:transform #(str "translate(" % ")")
              :r 5}))