以下代码用于显示 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; });
这里使用了 svg,它没有自动换行功能。我该如何更改这个普通段落
以便我可以使用 css 将其自动换行。如何制作此常规文本而不是 svg 文本?
最佳答案
这是使用 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
}
关于javascript - 将 SVG 文本更改为 css 自动换行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12677878/