Polygon select cells

by Nick Karnik

CSS

svg 
{
    margin: 30px; 
}

.brush .extent 
{
    stroke: #337788;
    stroke-width: 2px;
    stroke-dasharray: 1,3;
    fill: #337788;
    fill-opacity: 0.1;
}
.voronoi 
{
    fill: steelblue; 
    fill-opacity: 0.2;
}
.voronoi.selected 
{
    fill: red; 
    fill-opacity: 0.4;
}

.point 
{
    fill: silver;
    fill-opacity: 0.4;
}

.point.selected 
{
    fill: red;
}

JavaScript

var factor = 12, /* cells per side */
    dim = 50,
    w = dim * factor,
    h = dim * factor;

var vertices = d3.range(factor * factor).map(function (i) {
    return [(i % factor) * dim + dim / 2, Math.floor(i / factor) * dim + dim / 2];
});

var svg = d3.select("body")
    .append("svg")
    .attr("id", "grid")
    .attr("width", w)
    .attr("height", h);

(function (d3) {
    /* http://bl.ocks.org/GerHobbelt/3732612 */
    d3.svg.polybrush = function () {
        var dispatch = d3.dispatch("brushstart", "brush", "brushend"),
            x = null,
            y = null,
            extent = [],
            firstClick = true,
            firstTime = true,
            wasDragged = false,
            origin = null,
            line = d3.svg.line()
                .x(function (d) {
                    return d[0];
                })
                .y(function (d) {
                    return d[1];
                });
        var brush = function (g) {
            g.each(function () {
                var bg, e, fg;
                g = d3.select(this);
                bg = g.selectAll(".background").data([0]);
                fg = g.selectAll(".extent").data([extent]);
                g.style("pointer-events", "all").on("click.brush", addAnchor);
                bg.enter().append("rect").attr("class", "background").style("visibility", "hidden").style("cursor", "crosshair");
                fg.enter().append("path").attr("class", "extent").style("cursor", "move");
                if (x) {
                    e = scaleExtent(x.range());
                    bg.attr("x", e[0]).attr("width", e[1] - e[0]);
                }
                if (y) {
                    e = scaleExtent(y.range());
                    bg.attr("y", e[0]).attr("height", e[1] - e[0]);
                }
            });
        };
        var drawPath = function () {
            return d3.selectAll("g path").attr("d", function (d) {
                return line(d) + "Z";
            });
       ...