JSFiddle - React, Tailwind, and code Playground

by joshmoto

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<body>

</body>

CSS

.as-console-wrapper {
   max-height: 20% !important;
 }
 
 SVG {
   background: red;
 }

 path {
   fill: none;
   stroke: black;
   shape-rendering: crispEdges;
 }

 line {
   shape-rendering: crispEdges;
   stroke: black;
 }

JavaScript

var width = 400,
           height = 500;

   var data = [10, 15, 20, 25, 30];
   var svg = d3.select("body")
           .append("svg")
           .attr("width", width)
           .attr("height", height)
           .on("mousedown", mousedown)
           .on("mouseup", mouseup);


   var xscale = d3.scale.linear()
           .domain([0, d3.max(data)])
           .range([0, width - 100]);

   var yscale = d3.scale.linear()
           .domain([0, d3.max(data)])
           .range([height / 2, 0]);

   svg.on("mousemove", function() {
      console.log("x - using invert", xscale.invert(d3.mouse(this)[0] - 50));
      console.log("y- using invert", yscale.invert(d3.mouse(this)[1] - 10));
   });

   var x_axis = d3.svg.axis()
           .scale(xscale).orient("bottom");

   var y_axis = d3.svg.axis()
           .scale(yscale).orient("left");;

   svg.append("g")
           .attr("transform", "translate(50, 10)")
           .call(y_axis);

   var xAxisTranslate = height / 2 + 10;

   svg.append("g")
           .attr("transform", "translate(50, " + xAxisTranslate + ")")
           .call(x_axis)


   function mousedown() {
      var m = d3.mouse(this);
      line = svg.append("line")
              .attr("x1", m[0])
              .attr("y1", m[1])
              .attr("x2", m[0])
              .attr("y2", m[1]);
              
              Math.sqrt((m[0] - line.attr("x1")) ** 2 + (m[1] - line.attr("y1")) ** 2)
              text = svg.append("text")
        .attr("x", m[0])
        .attr("y", m[1])
        .style("user-select", "none")


      svg.on("mousemove", mousemove);
   }

   function mousemove() {
      var m = d3.mouse(this);
      line.attr("x2", m[0])
              .attr("y2", m[1]);
              
              var dist = Math.sqrt((m[0] - line.attr("x1")) ** 2 + (m[1] - line.attr("y1")) ** 2)
text
  .text(dist.toFixed(2))
  .attr("x", m[0] + 10)
  .attr("y", m[1])
  
   }

   function mouseup() {
      svg.on("mousemove", null);
      text.remove()
   }