[英]Draw properly sized rectangle around text
當用戶將鼠標懸停在餅圖上時,我正在嘗試在 hover 上繪制彈出工具提示。 以下工作,但問題是矩形是固定大小。 go 如何使矩形適合實際文本的大小?
// 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);
使用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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.