如何在javascript中换行svg文本? [英] How to linebreak an svg text in javascript?

查看:615
本文介绍了如何在javascript中换行svg文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从d3.js开始,我试图创建一个网络图,每个圆包含一个标签。

I am starting with d3.js, and am trying to create a network graph each circle of which contains a label.

我想要的是一个换行符svg文本。

What I want is a line break an svg text.

我想要做的是将文本分成多个< tspan> 每个具有x =0和变量y以模拟实际文本行。我写的代码给出了一些意想不到的结果。

What I am trying to do is to break the text into multiple <tspan>s, each with x="0" and variable "y" to simulate actual lines of text. The code I have written gives some unexpected result.

var text = svg.selectAll("text").data(force.nodes()).enter().append("text");

text       
 .text(function (d) {
 arr = d.name.split(" ");
 var arr = d.name.split(" ");
 if (arr != undefined) {
  for (i = 0; i < arr.length; i++) {
   text.append("tspan")
    .text(arr[i])
    .attr("class", "tspan" + i);
  }
 }
});

在此代码中,将文本字符串按白色空格分隔,并将每个拆分后的字符串附加到tspan。但属于其他圆的文本也显示在每个圆中。如何克服此问题?

In this code am splitting the text string by white space and appending the each splitted string to tspan. But the text belonging to other circle is also showing in each circle. How to overcome this issue?

以下是一个JSFIDDLE http:/ /jsfiddle.net/xhNXS/ 只有svg文本

Here is a JSFIDDLE http://jsfiddle.net/xhNXS/ with only svg text

这里是一个JSFIDDLE http://jsfiddle.net/2NJ25/16/ 显示我的tspan问题。

Here is a JSFIDDLE http://jsfiddle.net/2NJ25/16/ showing my problem with tspan.

推荐答案

您需要指定每个 tspan 元素的位置(或偏移量),以给出换行符的印象 - 它们实际上只是文本容器可任意定位。如果你包装 text 元素在 g 元素,这将是很容易,因为你可以指定绝对 ( x y )。这将使 tspan 元素移动到行的开头更容易。

You need to specify the position (or offset) of each tspan element to give the impression of a line break -- they are really just text containers that you can position arbitrarily. This is going to be much easier if you wrap the text elements in g elements because then you can specify "absolute" coordinates (i.e. x and y) for the elements within. This will make moving the tspan elements to the start of the line easier.

添加元素的主代码将会是这样。

The main code to add the elements would look like this.

text.append("text")       
    .each(function (d) {
    var arr = d.name.split(" ");
    for (i = 0; i < arr.length; i++) {
        d3.select(this).append("tspan")
            .text(arr[i])
            .attr("dy", i ? "1.2em" : 0)
            .attr("x", 0)
            .attr("text-anchor", "middle")
            .attr("class", "tspan" + i);
    }
});

我使用 .each() ,它将调用每个元素的函数,而不是期望返回值,而不是您正在使用的 .text() dy 设置指定行高,并且 x 设置为0意味着每个新行将从阻止。

I'm using .each(), which will call the function for each element and not expect a return value instead of the .text() you were using. The dy setting designates the line height and x set to 0 means that every new line will start at the beginning of the block.

修改jsfiddle 此处,以及一些其他次要清理。

Modified jsfiddle here, along with some other minor cleanups.

这篇关于如何在javascript中换行svg文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆