I want to calculate the distance while drawing the line on the vertical axis or horizontal axis. It could show next to the line of how much distance drawn from mousedraw or any other ways. Can someone help me?
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]);
svg.on("mousemove", mousemove);
}
function mousemove() {
var m = d3.mouse(this);
line.attr("x2", m[0])
.attr("y2", m[1]);
}
function mouseup() {
svg.on("mousemove", null);
}
Please check the live output I have now: https://jsfiddle.net/anojansith/m38b5fnp/1/