如何在 javascript 中对 svg 文本进行换行?

IT技术 javascript svg newline line-breaks
2021-01-16 09:44:46

所以这就是我所拥有的:

<path class="..." onmousemove="show_tooltip(event,'very long text 
    \\\n I would like to linebreak')" onmouseout="hide_tooltip()" d="..."/>

<rect class="tooltip_bg" id="tooltip_bg" ... />
<text class="tooltip" id="tooltip" ...>Tooltip</text>

<script>
<![CDATA[
function show_tooltip(e,text) {
    var tt = document.getElementById('tooltip');
    var bg = document.getElementById('tooltip_bg');

    // set position ...

    tt.textContent=text;

    bg.setAttribute('width',tt.getBBox().width+10);
    bg.setAttribute('height',tt.getBBox().height+6);

    // set visibility ...
}
...

现在我很长的工具提示文本没有换行符,即使我使用了 alert(); 它告诉我文本实际上有两行。(虽然它包含一个“\”,但我该如何删除它?)
我无法让 CDATA 在任何地方工作。

6个回答

这不是 SVG 1.1 支持的东西。SVG 1.2 确实具有textArea自动换行元素,但并非在所有浏览器中都实现了。SVG 2不打算实现textArea,但它确实有自动换行文本

但是,鉴于您已经知道应该在哪里换行,您可以将文本分成多个<tspan>s,每个都带有x="0"dy="1.4em"以模拟实际的文本行。例如:

<g transform="translate(123 456)"><!-- replace with your target upper left corner coordinates -->
  <text x="0" y="0">
    <tspan x="0" dy="1.2em">very long text</tspan>
    <tspan x="0" dy="1.2em">I would like to linebreak</tspan>
  </text>
</g>

当然,由于您想从 JavaScript 执行此操作,因此您必须手动创建每个元素并将其插入到 DOM 中。

试了一下 var tspan = document.createElement('tspan') tspan.setAttribute('x','0'); tspan.setAttribute('dy','1.2em'); tspan.textContent = text; tt.appendChild(tspan); 根本不显示任何文字。
2021-03-13 09:44:46
x=0是绝对坐标:将文本片段移动到当前坐标系的原点transform该属性上的g元件定义了一个新的当前坐标系,并假设文本是左对齐,所述TSPAN被移动到左边。这就像一个回车指令。 dy=1.2em是一个相对坐标:将文本片段移动这个量,相对于当前文本片段。这就像一个换行指令。结合起来,您将获得 CR/LF。
2021-03-15 09:44:46
您愿意详细说明为什么需要x='0' dy='1.2em'吗?它确实有效,就像你说的那样。但是,我希望它即使没有这些属性也能工作。相反,没有显示任何内容......此外,我并不完全清楚为什么会发生换行这不像我们已经将容器的宽度设置为固定的东西,以便它可以强制换行,是吗?
2021-03-22 09:44:46
我如何识别放在哪里<tspan>s代替?分裂?
2021-04-04 09:44:46
还没有尝试过:你也可以在没有小组的情况下这样做吗?<text x="100" y="100"><tspan x="100" y="100">很长的文字</tspan><tspan x="100" y="115">我想要换行</tspan></text> ??
2021-04-06 09:44:46

我想你已经设法解决了它,但是如果有人正在寻找类似的解决方案,那么这对我有用:

 g.append('svg:text')
  .attr('x', 0)
  .attr('y', 30)
  .attr('class', 'id')
  .append('svg:tspan')
  .attr('x', 0)
  .attr('dy', 5)
  .text(function(d) { return d.name; })
  .append('svg:tspan')
  .attr('x', 0)
  .attr('dy', 20)
  .text(function(d) { return d.sname; })
  .append('svg:tspan')
  .attr('x', 0)
  .attr('dy', 20)
  .text(function(d) { return d.idcode; })

有 3 行用换行符分隔。

我正在使用 D3,你的方法对我有用。感谢您发布它。我发现我需要先删除旧的 tspan,然后再添加新的,如下所示:focus.selectAll("tspan").remove();
2021-03-23 09:44:46
FWIW:看起来 OP 使用的是纯 JavaScript;这个答案似乎是利用D3
2021-03-31 09:44:46
注意这种方法会嵌套 <tspan> 标签,因为它链接了 .append()。这可能会导致 CSS 的一些小问题,具体取决于您想要做什么。
2021-04-10 09:44:46
有关避免@seneyr 描述的嵌套的方法,请参见此处
2021-04-12 09:44:46

使用 tspan 解决方案,假设您事先不知道在哪里放置换行符:您可以使用我在此处找到的这个不错的功能:http : //bl.ocks.org/mbostock/7555321

对于给定的像素宽度,这会自动为长文本 svg 进行换行。

function wrap(text, width) {
  text.each(function() {
    var text = d3.select(this),
        words = text.text().split(/\s+/).reverse(),
        word,
        line = [],
        lineNumber = 0,
        lineHeight = 1.1, // ems
        y = text.attr("y"),
        dy = parseFloat(text.attr("dy")),
        tspan = text.text(null).append("tspan").attr("x", 0).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", 0).attr("y", y).attr("dy", ++lineNumber * lineHeight + dy + "em").text(word);
      }
    }
  });
}

我认为这可以满足您的要求:

function ShowTooltip(evt, mouseovertext){
    // Make tooltip text        
    var tooltip_text = tt.childNodes.item(1);
    var words = mouseovertext.split("\\\n");
    var max_length = 0;

    for (var i=0; i<3; i++){
        tooltip_text.childNodes.item(i).firstChild.data = i<words.length ?  words[i] : " ";
        length = tooltip_text.childNodes.item(i).getComputedTextLength();
        if (length > max_length) {max_length = length;}
    }

    var x = evt.clientX + 14 + max_length/2;
    var y = evt.clientY + 29;
    tt.setAttributeNS(null,"transform", "translate(" + x + " " + y + ")")

    // Make tooltip background
    bg.setAttributeNS(null,"width", max_length+15);
    bg.setAttributeNS(null,"height", words.length*15+6);
    bg.setAttributeNS(null,"x",evt.clientX+8);
    bg.setAttributeNS(null,"y",evt.clientY+14);

    // Show everything
    tt.setAttributeNS(null,"visibility","visible");
    bg.setAttributeNS(null,"visibility","visible");
}

它拆分文本\\\n并为每个将每个片段放在一个 tspan 中。然后它根据文本的最长长度和行数计算所需框的大小。您还需要更改工具提示文本元素以包含三个 tspan:

<g id="tooltip" visibility="hidden">
    <text><tspan>x</tspan><tspan x="0" dy="15">x</tspan><tspan x="0" dy="15">x</tspan></text>
</g>

这假设您永远不会超过三行。如果您想要多于三行,您可以添加更多 tspan 并增加 for 循环的长度。

为什么是它"\\\n"而不是"\n"
2021-04-09 09:44:46

使用 HTML 而不是 javascript

<html>
  <head><style> * { margin: 0; padding: 0; } </style></head>
  <body>
    <h1>svg foreignObject to embed html</h1>

    <svg
      xmlns="http://www.w3.org/2000/svg"
      viewBox="0 0 300 300"
      x="0" y="0" height="300" width="300"
    >

      <circle
        r="142" cx="150" cy="150"
        fill="none" stroke="#000000" stroke-width="2"
      />

      <foreignObject
        x="50" y="50" width="200" height="200"
      >
        <div
          xmlns="http://www.w3.org/1999/xhtml"
          style="
            width: 196px; height: 196px;
            border: solid 2px #000000;
            font-size: 32px;
            overflow: auto; /* scroll */
          "
        >
          <p>this is html in svg 1</p>
          <p>this is html in svg 2</p>
          <p>this is html in svg 3</p>
          <p>this is html in svg 4</p>
        </div>
      </foreignObject>

    </svg>

</body></html>

它是“SVG 中的 HTML”,对我来说是最好的解决方案!
2021-03-14 09:44:46
我想你的意思是“使用 SVG 而不是 JavaScript”
2021-03-30 09:44:46