Skip to content

Instantly share code, notes, and snippets.

@romsson
Last active December 3, 2017 14:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save romsson/568e166d702b4a464347 to your computer and use it in GitHub Desktop.
Save romsson/568e166d702b4a464347 to your computer and use it in GitHub Desktop.
Drawing rectangles d3.v4
license: mit
<!DOCTYPE html>
<meta charset="utf-8">
<style>
svg {
float: left;
border-bottom: solid 1px #ccc;
border-right: solid 1px #ccc;
margin-right: -1px;
margin-bottom: -1px;
}
rect {
opacity: 0.2;
}
</style>
<body>
<script src="//d3js.org/d3.v4.min.js"></script>
<script>
var width = 800,
height = 600;
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
.on("mousedown", mousedown)
.on("mouseup", mouseup);
function mousedown() {
var m = d3.mouse(this);
rect = svg.append("rect")
.attr("x", m[0])
.attr("y", m[1])
.attr("height", 0)
.attr("width", 0);
svg.on("mousemove", mousemove);
}
function mousemove(d) {
var m = d3.mouse(this);
rect.attr("width", Math.max(0, m[0] - +rect.attr("x")))
.attr("height", Math.max(0, m[1] - +rect.attr("y")));
}
function mouseup() {
svg.on("mousemove", null);
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment