我将一个文本组附加到图表中,并希望将所有文本元素向下移动最长字符串的宽度。
这是我的代码:
chart.append('g')
.selectAll('text')
.data(data)
.enter()
.append('text')
.style("text-anchor","start")
.text(function(d){return d.top;})
.attr("transform", function(d) {
return "translate (" + x(d.year) + ",
" + (this.getComputedTextLength()) + ") " + "rotate(-90)"
});
这给了我:
问题是this.getComputedTextLength()
分别得到每个字符串的长度。我想要的是将所有字符串向下移动最长字符串的宽度:
我无法通过固定长度进行简单转换的原因是我有更新功能来更改我的数据源。换句话说,文本字符串的长度不是恒定的。
答案 0 :(得分:2)
我要翻译g
包装文字:
var maxLen = 0;
var g = chart.append('g');
g.selectAll('text')
.data(data)
.enter()
.append('text')
.style("text-anchor","start")
.text(function(d){return d;})
.attr("transform", function(d, i) {
var len = this.getComputedTextLength();
if (len > maxLen) maxLen = len;
return "translate (" + (i * 20) + ",0)rotate(-90)";
});
g.attr("transform", "translate(10, "+ maxLen +")");
完整代码示例:
<!DOCTYPE html>
<html>
<head>
<script data-require="d3@3.5.3" data-semver="3.5.3" src="//cdnjs.cloudflare.com/ajax/libs/d3/3.5.3/d3.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body>
<script>
var data = "two roads diverge in yellow wooddddddddddddd and I took".split(" ");
var chart = d3.select('body')
.append('svg')
.attr('width', 500)
.attr('height', 500);
var maxLen = 0;
var g = chart.append('g');
g.selectAll('text')
.data(data)
.enter()
.append('text')
.style("text-anchor","start")
.text(function(d){return d;})
.attr("transform", function(d, i) {
var len = this.getComputedTextLength();
if (len > maxLen) maxLen = len;
return "translate (" + (i * 20) + ",0)rotate(-90)";
});
g.attr("transform", "translate(10, "+ maxLen +")");
</script>
</body>
</html>