score:0

Accepted answer

to get the position of the circle, just use a getter...

var value = circle.attr("cy");

and update a text variable (here named text) with the math to get the percentage:

text.text("value: " + ~~(100*(value-y1)/(y2-y1)) + "%")

here is the demo:

var width = 50;
	var height = 300;
  
  var canvas = d3.select("svg")
	  .attr("width", 1600)
	  .attr("height", 1000)
	  .datum({
	    x: width / 2,
	    y: height / 2,
	  });
    
	var radius = 10;
	var margin = 10;
	var y1 = margin;
	var y2 = height - margin;
	var x = width / 2;

	var drag = d3.behavior.drag()
	  .origin(function(d) {
	    return d;
	  })
	  .on("drag", dragmove);
    
  var text = canvas.append("text")
  	.attr("x", 50)
    .attr("y", height/2)
    .text("value: 50%")

	var line = canvas.append("line")
	  .attr("y1", y1)
	  .attr("y2", y2)
	  .attr("x1", x)
	  .attr("x2", x)
	  .style("stroke", "black")
	  .style("stroke-linecap", "round")
	  .style("stroke-width", 5);

	var circle = canvas.append("circle")
	  .attr("r", radius)
	  .attr("cy", function(d) {
	    return d.y;
	  })
	  .attr("cx", function(d) {
	    return d.x;
	  })
	  .style("cursor", "ew-resize")
	  .call(drag);
    
  	function dragmove(d) {
	  var y = d3.event.y;
	  y = y < y1 ? y1 : y > y2 ? y2 : y;
	  d.y = y;
	  circle.attr("cy", y);
    var value = circle.attr("cy");
    text.text("value: " + ~~(100*(value-y1)/(y2-y1)) + "%")
	}
<svg></svg>
<script src="https://d3js.org/d3.v3.min.js"></script>


Related Query

More Query from same tag