【问题标题】:svg text wrapping issuessvg 文本换行问题
【发布时间】:2017-07-21 19:35:50
【问题描述】:

我正在尝试将调用的数据包装成 svg 上的两行文本。现在它正在显示超过六行的文本。有人能帮忙吗。

    function wrap(text, width, content) {
    text.each(function () {
        var text = d3.select(this),
            words = content.split(/\s+/).reverse(),
            word,
            line = [],
            lineNumber = 0,
            lineHeight = 1, // ems
            x = text.attr("x"),
            y = text.attr("y"),
            dy = 0, //parseFloat(text.attr("dy")),
            tspan = text.text(null)
                        .append("tspan")
                        .attr("x", x)
                        .attr("y", y)
                        .attr("dy", dy + "em");
        while (word = words.pop()) {
            line.push(word);
            tspan.text(line.join(''));
            if (tspan.node().getComputedTextLength() > width) {
                line.pop();
                tspan.text(line.join(" "));
                line = [word];
                tspan = text.append("tspan")
                            .attr("x", x)
                            .attr("y", y)
                            .attr("dy", ++lineNumber * lineHeight + dy + "em")
                            .text(word);
            }
        }
    });
}

  Thermometer.prototype.drawTick = function(t, label, labelColor, textOffset, width, tubeWidth, lineColor, scale, svg) {

    svg.append("line")
      .attr("id", label + "Line")
      .attr("x1", width / 2 - tubeWidth / 2)
      .attr("x2", width / 2 + tubeWidth / 2)
      .attr("y1", scale(t))
      .attr("y2", scale(t))
      .style("stroke", lineColor)
      .style("stroke-width", "2px")
      .style("shape-rendering", "crispEdges");
    if (label) {
      svg.append("text")
        .attr("x", width / 2 + tubeWidth / 2 + 15)
        .attr("y", scale(t))
        .attr("dy", ".5em")
        .text(label)
        .style("fill", labelColor)
        .style("stroke", "black")
        .style("font-size", "14px")
        .call(wrap,30,label)
    }
  };
  return Thermometer;

我的小提琴的链接在这里 https://jsfiddle.net/corcorancr/sxs5n2cw/1/

【问题讨论】:

  • 我没有看到任何变化???
  • 我猜这段代码不是你自己写的(?)很容易弄清楚为什么会这样。您尝试过如何调试它?
  • 如果方便的话请帮忙
  • @PaulLeBeau 不,它来自from here
  • 根据此处的情况,您似乎复制了问题中的大部分代码。虽然 SO 不会经常涉及版权问题,但不注明代码来源是抄袭,这在 Stack Overflow(或 Stack Exchange 上的任何地方)都是不可接受的。至少,请包含指向原始来源的链接。如果代码来自另一个 Stack Overflow 问题,则 CC BY-SA 3.0 许可证需要 more detailed attribution

标签: svg svg.js


【解决方案1】:

drawTick() 函数正在调用另一个名为 wrap() 的函数来绘制文本。正如该名称所暗示的那样,wrap() 将输入文本拆分为单词,如果它比您传入的宽度更宽,则将其换行。

宽度值是下面一行中的“30”:

.call(wrap,30,label)

试着把它改成更大的,这样它就不会这么快换行了。 180 似乎是正确的值。

https://jsfiddle.net/sxs5n2cw/4/

【讨论】:

    猜你喜欢
    • 2017-12-27
    • 1970-01-01
    • 2016-07-19
    • 2016-02-23
    • 1970-01-01
    • 1970-01-01
    • 2022-01-16
    • 2019-12-30
    • 1970-01-01
    相关资源
    最近更新 更多