【问题标题】:How to fit the text in rectangle box of my svg in d3.js?如何在 d3.js 中适合我的 svg 矩形框中的文本?
【发布时间】:2015-07-28 09:29:03
【问题描述】:

我正在使用 d3.js 可视化来描绘节点。我现在正在收到文本。我有一个代码来调整矩形的宽度,具体取决于进入它的文本长度。但是,有时它不起作用,文本超出了矩形框。这是它的代码。

nodeEnter.append("rect").attr("x",
        function(d) {
            var x = d.name.length;
            x = x + 150;
            return -(x) / 2;
        }).attr("y", -10).attr(
        "width",
        function(d) {
            var x = d.name.length;
            x = x + 150;
            return x;
        }).attr("height", 20).style({
        "fill": function(d) {
            return d._children ? "lightsteelblue" : "#fff";
        },
        "stroke": "steelblue",
        "stroke-width": "1.5px"
    });

    nodeEnter.append("text").attr("x", 0).attr("y", 0)
        .attr("dy", ".35em").attr(
            "text",
            function(d) {
                return d.children || d._children ? "end" : "start";
            }).text(function(d) {
            return d.name;
        }).style({
            "fill-opacity": 1e-6,
            "font-size": "10px",
            "font-family": "sans-serif"
        }).attr(
            "text-anchor", "start");

在这里,我将文本的长度放入框中并添加了 150。但是,没有超出一点。我可以在这里得到任何帮助吗?

根据使用 getBBox() 的建议。我尝试使用它,这是编辑后的代码

var text = nodeEnter.append("svg:text").attr("x", 0).attr("y", 0)
    .attr("dy", ".35em").attr(
        "text",
        function(d) {
            return d.children || d._children ? "end" : "start";
        }).text(function(d) {
        return d.name;
    }).style({
        "fill-opacity": 1e-6,
        "font-size": "10px",
        "font-family": "sans-serif"
    }).attr(
        "text-anchor", "middle");
    
    var bbox = text.node().getBBox();
    nodeEnter.append("rect").attr("x",
        function(d) {
            var x = d.name.length;
            x = x + 150;
            return -(x) / 2;
        }).attr("y", -10).attr(
        "width", bbox.width).attr("height", bbox.height)
        .style({
        "fill": function(d) {
            return d._children ? "lightsteelblue" : "#fff";
        },
        "stroke": "steelblue",
        "stroke-width": "1.5px"
    });

这会使矩形框内的文本消失,只有溢出的文本可见

【问题讨论】:

标签: javascript css d3.js svg


【解决方案1】:

首先创建具有恒定宽度的矩形。
然后创建文本元素并将边界框的宽度getBBox().width 作为属性添加到数据集(例如twidth)。
最后根据添加的属性(twidth)按宽度更新矩形元素。

【讨论】:

  • 先创建文本元素,然后根据getBBox.width()添加rect,使文本消失在框中。
  • @user3531436 你需要填充矩形吗?
  • 是的。我需要在矩形中显示文本
猜你喜欢
  • 1970-01-01
  • 2021-02-19
  • 1970-01-01
  • 2022-01-16
  • 1970-01-01
  • 1970-01-01
  • 2021-10-19
  • 2013-07-07
  • 2012-06-15
相关资源
最近更新 更多