[英]d3.js dynamic text wrapping
I am trying to create thin rectangle charts and I need a method that could take the text and wrap it properly. 我正在尝试创建薄矩形图,并且我需要一种可以将文本正确包装的方法。
The goal is to create something like this. 目标是创建类似这样的东西。
http://jsfiddle.net/0ht35rpb/167/ http://jsfiddle.net/0ht35rpb/167/
d3.js how to apply text wrapping declaratively Lars had come up with a solution - and I've tried to implement it here - but I couldn't get it to work. d3.js如何以声明方式应用文本换行 Lars提出了一个解决方案-我试图在这里实现它-但我无法使它正常工作。
http://jsfiddle.net/0ht35rpb/168/ http://jsfiddle.net/0ht35rpb/168/
const axisLabel = chart
.append("g")
.append("text")
.attr('x', function(d) {
return path.centroid(d)[0];
})
.attr('y', function(d) {
return path.centroid(d)[1] + 4;
})
.each(function(d) {
var arr = d.properties.eventname.split(" ");
if (arr != undefined) {
for (var i = 0; i < arr.length; i++) {
d3.select(this).append("tspan")
.text(function() {
return arr[i];
})
.attr("y", path.centroid(d)[1] + i * 8 + 8)
.attr("x", path.centroid(d)[0])
.attr("text-anchor", "middle");
}
}
});
there is this method here with tspans and this nearly works - but the text is not centered? tspans上有这种方法,几乎可以使用-但文字未居中?
http://jsfiddle.net/0ht35rpb/169/ http://jsfiddle.net/0ht35rpb/169/
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);
}
}
});
}
You don't have any path
in your code and, therefore, no centroid. 您的代码中没有任何
path
,因此没有质心。
Thus, it should be: 因此,应为:
.attr('x', function(d) {
return config.width / 2;
})
.attr('y', function(d) {
return config.height;
})
Here is your updated fiddle: http://jsfiddle.net/vumbvs9s/ 这是您更新的小提琴: http : //jsfiddle.net/vumbvs9s/
Regarding your second fiddle, just change Bostock's function to get the current x
position: 关于第二个小提琴,只需更改Bostock的函数以获取当前的
x
位置:
var x = text.attr("x");
Here is the updated fiddle: http://jsfiddle.net/a0s8h3wg/ 这是更新的小提琴: http : //jsfiddle.net/a0s8h3wg/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.