JSFiddle - React, Tailwind, and code Playground
HTML
<script src="http://d3js.org/d3.v3.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="http://d3js.org/d3.v3.min.js"></script>
<p class="intro">Click and drag in one of the boxes to highlight circles.</p>
<div id="canvases">
<div class="canvas" id="canvas1"></div>
</div>
CSS
body {
padding-left: 15px;
}
.intro {
font-size: 14px;
font-family: Arial, sans-serif;
}
#canvases {
width: 960px;
height: 300px;
}
.canvas {
float: left;
border: 1px solid gray;
width: 300px;
height: 300px;
margin-right: 10px;
}
svg {
cursor: crosshair;
}
circle {
fill: steelblue;
opacity: 0.75;
}
circle.highlighted {
fill: orange;
}
path {
stroke: #000;
stroke-width: 1;
fill: none;
}
text {
font-size: 10px;
text-anchor: middle;
pointer-events: none;
fill: #000;
font-family: Arial, sans-serif;
}
JavaScript
(function() {
var data = [],
width = 300,
height = 300,
// An array to hold the coordinates
// of the line drawn on each svg.
coords = [],
line = d3.svg.line(),
// Set the behavior for each part
// of the drag.
drag = d3.behavior.drag()
.on("dragstart", function() {
// Empty the coords array.
coords = [];
svg = d3.select(this);
// If a selection line already exists,
// remove it.
svg.select(".selection").remove();
// Add a new selection line.
svg.append("path").attr({"class": "selection"});
})
.on("drag", function() {
// Store the mouse's current position
coords.push(d3.mouse(this));
svg = d3.select(this);
// Change the path of the selection line
// to represent the area where the mouse
// has been dragged.
svg.select(".selection").attr({
d: line(coords)
});
// Figure out which dots are inside the
// drawn path and highlight them.
selected = [];
svg.selectAll("circle.dot").each(function(d, i) {
point = [d3.select(this).attr("cx"), d3.select(this).attr("cy")];
if (pointInPolygon(point, coords)) {
selected.push(d.id);
}
});
highlight(selected);
})
.on("dragend", function() {
svg = d3.select(this);
// If the user clicks without having
// drawn a path, remove any paths
// that were drawn...