How To Show The Barlength In Px Of A SVG Above The Mouse Pointer
I would like to show the barlength in px multiplied by 2, above the mouse pointer. I tried it with var txt = svg.append('text') and then txt.text(distance); but ended up with erro
Solution 1:
I made a few updates to your code:
- add a new variable for the text element
- create the text element on
mousedown
but don't add text yet - update the text element position on
mousemove
and calculate the label text from the distance betweenxy0
andxy1
, then make slight adjustment to the label position
To refine the label orientation with respect to the pointer and whether the pointer is dragging left/ right, up/ down; you can play with the dx
and dy
attributes where I have just hardcoded something reasonable for the purpose of the example.
function stretch(brush) {
var foo; // variable for text element
var xy0, bluebar, stay = false,
bar = d3.svg.line().x(function(d) {
return d[0];
}).y(function(d) {
return d[1];
});
brush.on('mousedown', function() {
stay = true;
xy0 = d3.mouse(this);
bluebar = d3.select('svg').append('path').attr('d', bar([xy0, xy0])).style({
'stroke': 'lightblue',
'stroke-width': '50px'
});
// append the element but no actual text
foo = d3.select('svg')
.append('text')
.attr('x', xy0[0])
.attr('y', xy0[1])
.text(""); // start with no text
}).on('mouseup', function() {
stay = false;
}).on('mousemove', function() {
if (stay) {
// new point
var xy1 = d3.mouse(this).map(function(x) {
return x - 1;
});
// your code to draw the bar
Bar = bar([xy0, xy1]);
bluebar.attr('d', Bar);
// formula for distance between two points (for text)
var dx = Math.abs(xy1[0] - xy0[0]);
var dy = Math.abs(xy1[1] - xy0[1]);
var d = Math.sqrt(Math.pow(dx, 2) + Math.pow(dy, 2));
// move and calculate the text
foo.attr('x', xy1[0])
.attr('y', xy1[1])
.text((d * 2).toFixed(0) + "px");
// orient the label
if (xy1[0] >= xy0[0]) {
foo.attr('dx', '0.35em');
} else {
foo.attr('dx', '-2.35em');
}
if (xy1[1] < xy0[1]) {
foo.attr('dy', '0em');
} else {
foo.attr('dy', '0.75em');
}
}
});
}
d3.select('body').append('svg').call(stretch);
<script src="https://d3js.org/d3.v3.min.js"></script>
Post a Comment for "How To Show The Barlength In Px Of A SVG Above The Mouse Pointer"