我有一个带有标题的d3图表。标题是图表。但是,在小屏幕上,文本需要换行以免溢出。
但是,Bl.ocks文本换行方法不是创建新行,而是为每个单词创建一个新的tspan,然后将每个文本/ tspan放在另一个顶部
这是问题的jsfiddle:此处的jsfiddle
这是相关的代码
var chartTitle = svg.append("text")
.attr("y", -15 )
.attr("text-anchor", "start")
.text("This is a very long chart title that should be wrapped!")
.attr('class','chartTitle')
.call(wrap, width/2);
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);
}
}
});
}
的CSS
.chartTitle{
font-size:20px;
}
该wrap
函数最初由Mike Bostock(D3创建者)编写,用于包装标签,该函数使用textdy
属性(由轴生成器自动创建)。就是说,您的代码的问题dy
在于该文本元素中没有属性。
您可以简单地调整函数或仅设置零dy
属性。这是使用后者的演示:
var svg = d3.select("body")
.append("svg");
var chartTitle = svg.append("text")
.attr("y", 20)
.attr("dy", 0)//set the dy attribute
.attr("text-anchor", "start")
.text("This is a very long chart title that should be wrapped!")
.attr('class', 'chartTitle')
.call(wrap, 300 / 2);
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);
}
}
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句