<!doctype html>

<html>
  <head>
  </head>

  <body>
    <svg id="draw" width="500" height="300" style="border:1px solid black;"></svg>
    <h2>Click + drag your mouse above to draw rectangles.</h2>

    <script src="https://d3js.org/d3.v3.min.js"></script>
    <script src="script.js"></script>
  </body>
</html>
let startCoords = {};
let rect = null;
let el = document.querySelector("#draw");

el.addEventListener("mousedown", function(event){
  startCoords.x = event.x;
  startCoords.y = event.y;
  startCoords.hasClicked = true;
});

el.addEventListener("mouseup", function(event){
  rect
    .attr("width", Math.abs(startCoords.x - event.x))
    .attr("height", Math.abs(startCoords.y - event.y))
    .attr("x", Math.min(startCoords.x, event.x))
    .attr("y", Math.min(startCoords.y, event.y));

  rect = null;
  startCoords.hasClicked = false;
});

el.addEventListener("mousemove", function(event){
  //don't draw when mouse is moving around inside drawing element without clicking yet
  if(!startCoords.hasClicked) return;

  if(!rect){
    rect = d3.select(el)
      .append("rect");
  }
  
  rect
    .attr("width", Math.abs(startCoords.x - event.x))
    .attr("height", Math.abs(startCoords.y - event.y))
    .attr("x", Math.min(startCoords.x, event.x))
    .attr("y", Math.min(startCoords.y, event.y))
    .attr("fill-opacity", 0)
    .attr("stroke", "black")
    .attr("stroke-width", 0.3);
})