我已经找到了一些示例,但很难让任何示例发挥作用,如果有人有更清晰的见解或一些见解,我们将不胜感激。
var wrap = function() {
var self = d3.select(this),
textLength = self.node().getComputedTextLength(),
text = self.text();
while (textLength > (50) && text.length > 0) {
text = text.slice(0, -1);
self.text(text + '...');
textLength = self.node().getComputedTextLength();
}
};
const y = d3.scaleBand()
.range([height, 0], .1)
.domain(data.map(function (d) {
return d.name; <----- wrap need to somehow attach to this
})
);
最佳答案
无论您尝试做什么,您的方法的问题是 getComputedTextLength()
对 imaginary 元素或未附加到的数据不起作用一个元素...它只适用于真正的 SVG 元素,出现在 SVG 上。
但是,由于您想将该字符串数组传递给带刻度的域,我们通常在呈现元素之前设置,所以在我看来您想要 trim 长字符串事先。
如果那是正确的,一种可能的方法是渲染一个临时元素,只是为了获得它的计算文本长度, trim 它,创建一个新字符串并丢弃临时元素。
所以,假设我们有这个数据数组:
var data = ["A very long long long text here",
"another very very long piece of text in this string",
"finally, here we have another very big string"
];
我们可以使用您的 wrap 函数的修改版本来 trim 字符串。这是一个演示,检查控制台:
var data = ["A very long long long text here",
"another very very long piece of text in this string",
"finally, here we have another very big string"
];
var svg = d3.select("svg");
data.forEach(wrap);
function wrap(d, i, arr) {
var self = svg.append("text")
.text(d);
var textLength = self.node().getComputedTextLength();
while (textLength > 50 && d.length > 0) {
arr[i] = arr[i].slice(0, -1);
self.text(arr[i] + '...');
textLength = self.node().getComputedTextLength();
}
arr[i] += "...";
self.remove();
}
console.log(data)
<script src="https://d3js.org/d3.v5.min.js"></script>
<svg></svg>
因为它使用了真实的元素,所以字体大小之类的东西很重要。例如,将上面的结果与下面的结果进行比较,使用另一种字体和字体大小:
var data = ["A very long long long text here",
"another very very long piece of text in this string",
"finally, here we have another very big string"
];
var svg = d3.select("svg");
data.forEach(wrap);
function wrap(d, i, arr) {
var self = svg.append("text")
.text(d);
var textLength = self.node().getComputedTextLength();
while (textLength > 50 && d.length > 0) {
arr[i] = arr[i].slice(0, -1);
self.text(arr[i] + '...');
textLength = self.node().getComputedTextLength();
}
arr[i] += "...";
self.remove();
}
console.log(data)
text {
font-size: 8px;
font-family: "Arial Narrow";
}
<script src="https://d3js.org/d3.v5.min.js"></script>
<svg></svg>
但是,请记住 getComputedTextLength()
显然会忽略 letter-spacing
之类的内容,如您在此处所见:Compute textlength with letter-spacing with D3.js
关于javascript - 长文本的省略号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51957049/