繁体   English   中英

在文本周围绘制适当大小的矩形

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM