block by aaizemberg 45aaf921848d45fd9e52640cb690ae1b

d3-brush mini example

Full Screen

index.html

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>d3-brush</title>
</head>
<body>
  <h1>d3-brush</h1>
  <h2>Draw a rectangle (inside the box)</h2>
  <p>open and view the Console</p>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.2.3/d3.min.js"></script>

<script>
var width = 400;
var height = 400;

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

svg.append("rect").attr("width",width).attr("height",height).style("fill","none").style("stroke","black");

var brush = d3.brush()
    .extent([[0, 0], [width, height]])
    .on("start brush", brushed)
    .on("end", brushended);

svg.append("g")
    .attr("class", "brush")
    .call(brush);

function brushed() {
  // console.log( d3.event.selection );
  var s = d3.event.selection,
      x0 = s[0][0],
      y0 = s[0][1],
      x1 = s[1][0],
      y1 = s[1][1],
      dx = s[1][0] - x0,
      dy = s[1][1] - y0;
  console.log("("+x0+","+y0+")-("+x1+","+y1+")");
}

function brushended() {
  console.log('end');
  if (!d3.event.selection) {
    console.log('There is no selection');
  }   
}  
</script>    
  
</body>
</html>