I'm trying to draw a popup tooltip on hover when the user mouses over a pie chart. The following works, but the problem is the rectangle is a fixed size. How might one go about making the rectangle fit the size of the actual text?
// Draw rectangle
popup
.append("rect")
.attr("x", x + 5)
.attr("y", y - 5)
.attr("width", width)
.attr("height", height)
.attr("rx", 5)
.attr("ry", 5)
.style("fill", popupFillColor)
.style("stroke", stroke)
.style("stroke-width", 2);
// add text
popup
.append("text")
.attr("x", x + 10)
.attr("y", y + 10)
.text(e.seriesValue[0] + `: ${e.pValue} (${percent})`)
.style("font-family", "sans-serif")
.style("font-size", 14)
.style("fill", stroke);
Use getBBox :
const x = 50, y = 30; const svg = d3.select('svg'); const rect = d3.select('svg').append('rect').style('fill', 'none').style('stroke', 'black'); const text = svg.append('text').text('This is my text').attr('x', x).attr('y', y) const box = text.node().getBBox(); console.log(box) const X_MARGIN = 20; const Y_MARGIN = 10; rect.attr('x', box.x - X_MARGIN).attr('y', box.y - Y_MARGIN).attr('width', box.width + X_MARGIN * 2).attr('height', box.height + Y_MARGIN * 2)
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script> <svg></svg>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.