【发布时间】:2018-01-24 18:10:13
【问题描述】:
在 D3 中,我想包装具有中间文本锚点的文本。我查看了this example from Mike Bostok,但无法完全理解这些设置。
我希望文本位于红色框的中心(水平和垂直)。
var plot = d3.select(container)
.insert("svg")
.attr('width', 100)
.attr('height', 200);
plot.append("text")
.attr("x", 50)
.attr("y", 100)
.attr("text-anchor", "middle")
.attr("alignment-baseline", "alphabetic")
.text("The brown fox jumps!")
.call(wrap, 100);
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 = 1,
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);
}
}
});
}
鉴于来自Shashank 的指针,我现在可以使用 translate 方法将文本定位在中心位置。只是设置文本的 y 似乎并没有改变任何东西。我还添加了一个 yTrack 变量,以便能够在包裹的文本下方继续绘图。
let yTrack = 100,
plot = d3.select(container)
.insert("svg")
.attr('width', 100)
.attr('height', 200);
plot.append("text")
.attr("x", 50)
.attr("y", yTrack)
.attr("text-anchor", "middle")
.attr("font-family", "sans-serif")
.text("The quick brown fox jumps over the lazy dog.")
.call(wrap, 100);
let height = parseInt(plot.select('text').node().getBoundingClientRect().height);
plot.select("text").attr('transform', 'translate(0, ' + (-height / 2) + ')');
//plot.select("text").attr('y', 0);
yTrack += (parseInt(height / 2) + 10);
plot.append('rect')
.attr("x", 0)
.attr("y", yTrack)
.attr("width", 100)
.attr("height", 10)
.style('fill', '#999');
function wrap(text, width) {
text.each(function() {
let text = d3.select(this),
words = text.text().split(/\s+/).reverse(),
word,
line = [],
lineNumber = 0,
lineHeight = 1.1, // ems
x = text.attr("x"),
y = text.attr("y"),
dy = 1.1,
tspan = text.text(null).append("tspan").attr("x", x).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", x).attr("y", y).attr("dy", ++lineNumber * lineHeight + dy + "em").text(word);
}
}
});
}
#container {
height: 200px;
width: 100px;
border: 1px solid red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<div id="container"></div>
【问题讨论】:
-
Regulär svg 文本无法轻松重新定位。您可能会考虑将文本放入
中。然后你可以使用css和html