Skip to content

Instantly share code, notes, and snippets.

@lgersman
Last active August 3, 2019 13:43
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save lgersman/5310854 to your computer and use it in GitHub Desktop.
Save lgersman/5310854 to your computer and use it in GitHub Desktop.
d3.js selection frame example.
  • Click into the drawing area to start the selection frame
  • move the mouse to resize the selection frame
  • Release the mouse button to resize the selection frame

(The circles are just for illustrating purposes)

See it live : http://bl.ocks.org/lgersman/5310854

.selection {
stroke : gray;
stroke-width : 1px;
stroke-dasharray: 4px;
stroke-opacity : 0.5;
fill : transparent;
}
.state {
stroke : gray;
fill : white;
}
var states = [
{ x : 43, y : 67, label : "first" },
{ x : 340, y : 150, label : "second" },
{ x : 300, y : 350, label : "third" },
{ x : 300, y : 350, label : "fourth" },
{ x : 50, y : 270, label : "fifth" },
{ x : 90, y : 400, label : "last" }
]
window.svg = d3.select("body")
.append("svg")
.attr("width", "960px")
.attr("height", "500px");
svg.selectAll( ".state")
.data( states)
.enter()
.append( "circle")
.attr({
class : 'state',
r : 40,
cx : function( state) {
return state.x;
},
cy : function( state) {
return state.y;
}
})
.on("mouseover", function(){d3.select(this).style("fill", "aliceblue");})
.on("mouseout", function(){d3.select(this).style("fill", "white");});
;
svg
.on( "mousedown", function() {
var p = d3.mouse( this);
svg.append( "rect")
.attr({
rx : 6,
ry : 6,
class : "selection",
x : p[0],
y : p[1],
width : 0,
height : 0
})
})
.on( "mousemove", function() {
var s = svg.select( "rect.selection");
if( !s.empty()) {
var p = d3.mouse( this),
d = {
x : parseInt( s.attr( "x"), 10),
y : parseInt( s.attr( "y"), 10),
width : parseInt( s.attr( "width"), 10),
height : parseInt( s.attr( "height"), 10)
},
move = {
x : p[0] - d.x,
y : p[1] - d.y
}
;
if( move.x < 1 || (move.x*2<d.width)) {
d.x = p[0];
d.width -= move.x;
} else {
d.width = move.x;
}
if( move.y < 1 || (move.y*2<d.height)) {
d.y = p[1];
d.height -= move.y;
} else {
d.height = move.y;
}
s.attr( d);
//console.log( d);
}
})
.on( "mouseup", function() {
svg.select( ".selection").remove();
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>d3.js selection frame example</title>
<link rel="stylesheet" href="app.css">
</head>
<body>
</body>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script src="app.js"></script>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment