javascript 将 SVG 文本更改为 css 自动换行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12677878/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 16:50:43  来源:igfitidea点击:

change SVG text to css word wrapping

javascriptcsssvgd3.jsword-wrap

提问by user1704514

The following code is used to show the text labels of a javascript tree diagram.

以下代码用于显示 javascript 树状图的文本标签。

nodeEnter.append("svg:text")
        .attr("x", function(d) { return d._children ? -8 : -48; }) /*the position of the text (left to right)*/
        .attr("y", 3) /*the position of the text (Up and Down)*/

        .text(function(d) { return d.name; });

This uses svg, which has no word wrapping ability. How do I change this do a normal paragraph

这使用 svg,它没有自动换行能力。我如何改变这个做一个正常的段落

so that I may use css to word wrap it. How do I make this regular text and not svg text?

这样我就可以使用 css 对其进行自动换行。如何制作此常规文本而不是 svg 文本?

采纳答案by Matti John

You probably want to use the SVG foreignObject tag, so you would have something like this:

您可能想要使用 SVG foreignObject 标记,因此您将拥有如下内容:

nodeEnter.append("foreignObject")
    .attr("x", function(d) { return d._children ? -8 : -48; }) /*the position of the text (left to right)*/
    .attr("y", 3) /*the position of the text (Up and Down)*/
    .attr("width", your_text_width_variable)
    .attr("height", your_text_height_variable)
    .append("xhtml:body")
    .append("p")
    .text(function(d) { return d.name; });

Here is a gist by Mike Bostock which helped me: https://gist.github.com/1424037

这是 Mike Bostock 的一个要点,它帮助了我:https: //gist.github.com/1424037

回答by IsidroGH

This is a sample code to word-wrap texts with D3:

这是使用 D3 自动换行文本的示例代码:

var nodes = [
    {title: "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut"}
]

var w = 960, h = 800;

var svg = d3.select("body").append("svg")
    .attr("width", w)
    .attr("height", h);

var vSeparation = 13, textX=200, textY=100, maxLength=20

var textHolder = svg.selectAll("text")
    .data(nodes)
    .enter().append("text")
    .attr("x",textX)
    .attr("y",textY)
    .attr("text-anchor", "middle")
    .each(function (d) {
        var lines = wordwrap(d.title, maxLength)

        for (var i = 0; i < lines.length; i++) {
            d3.select(this).append("tspan").attr("dy",vSeparation).attr("x",textX).text(lines[i])
        }
    });


function wordwrap(text, max) {
    var regex = new RegExp(".{0,"+max+"}(?:\s|$)","g");
    var lines = []

    var line
    while ((line = regex.exec(text))!="") {
        lines.push(line);
    } 

    return lines
}

回答by Matti John

foreignObjectisn't supported by IE and Chrome doesn't support transitions on it. If those limitations are okay then I recommend using foreignObjectbecause you get all of the formatting of HTML+CSS.

foreignObjectIE 不支持,Chrome 也不支持它的转换。如果这些限制没问题,那么我建议使用,foreignObject因为您可以获得 HTML+CSS 的所有格式。

If you need to support IE or transitions then I suggest using a D3 plugin such as D3plus. It makes text wrapping very easy.

如果您需要支持 IE 或转换,那么我建议使用 D3 插件,例如D3plus。它使文本换行非常容易。

d3plus.textwrap()
  .container('selector')
  .draw();

Checkout the docsto read about all of its features.

查看文档以了解其所有功能。

回答by domenu

You can use this generic function using D3.js to wrap text in an svg:text element into multiple svg:tspan children (one tspan per line):

您可以使用 D3.js 使用此通用函数将 svg:text 元素中的文本包装成多个 svg:tspan 子元素(每行一个 tspan):

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

You can use it like this:

你可以这样使用它:

svg.selectAll('text').call(wrapText, 100);