我使用D3,js创建了一个简单的条形图,并遇到了文本颜色问题 . 当文本在栏内时它看起来很好,但如果文本太长则变得不可读 .
如何根据红色矩形宽度更改文本颜色(如果文本在矩形内 - 否则为默认颜色 - 其他颜色并使其在Chrome / FF / IE11 / Edge中工作,如果可能的话?
将文字附加到栏:
bar.append("text")
.attr('class', 'x-name-text')
.attr("x", 10)
.attr("y", barHeight / 2)
.attr("dy", ".35em")
.text(function(d) {
return d.name;
});
UPDATE: 可能的解决方案:
1)追加下层 text :
bar.append("text")
.attr('class', 'x-name-text')
.attr("x", 10)
.attr("y", barHeight / 2)
.attr("fill", "red")
.attr("dy", ".35em")
.text(function(d) {
return d.name;
});
2)追加 rect :(不要忘记每个 rect 的唯一 id )
bar.append("rect")
.attr("fill", color(0))
.attr("id", function(d) {
return d.id;
})
...
3)追加 clipPath 并使用相同的 id 将其与 xlink:href 链接到必要的 rect :
// clipPath depending on rect width
bar.append('clipPath')
.attr('id', function(listItem, index) {
return listItem.id + '' + index;
})
.append('use')
.attr('xlink:href', function(listItem){
return '#' + listItem.id;
});
4)追加覆盖 text 的 clip-path 样式属性链接到 clipPath SVG元素的id:
bar.append('text')
.attr("x", 10)
.attr("y", barHeight / 2)
.attr("dy", ".35em")
.attr('class', 'overflow-name')
.style('clip-path', function(listItem, index) {
return 'url(#' + listItem.id + '' + index + ')';
})
.text(function(d) {
return d.name;
});