简体   繁体   English

水平条形图上的文字-d3

[英]Text on horizontal bar chart - d3

I have a horizontal bar chart on which i'm displaying the field name. 我有一个水平条形图,上面显示了字段名称。 If the name(text) exceeds the bar , the text has to be in black color like in below. 如果名称(文本)超过了条形,则文本必须为黑色,如下所示。 How would i do that? 我该怎么办?

This is not a trivial thing to do. 这不是一件容易的事。 You would have to 你将不得不

  • Add the text. 添加文字。
  • Determine its actual dimensions using .getBBox() or something similar. 使用.getBBox()或类似方法确定其实际尺寸。
  • Remove the text. 删除文本。
  • Split the text into separate segments (eg tspan s) depending on its actual width and the width of the bar. 根据文本的实际宽度和条的宽度,将文本分成单独的段(例如tspan )。
  • Add those segments with the respective styles. 使用相应的样式添加这些细分。

That is, you would have to manually break up the text into the parts that you want different styles for and then assign those styles. 也就是说,您将必须手动将文本分解成想要不同样式的部分,然后分配这些样式。

I've managed to do it using two text labels. 我设法使用两个文本标签来做到这一点。 Top label is wrapped in svg so it clips its length. 顶部标签包裹在svg中,因此可以缩短其长度。 Here is working example - http://jsfiddle.net/cuckovic/C6SSj/ 这是工作示例-http://jsfiddle.net/cuckovic/C6SSj/

bar.append("text")
    .attr("class", "below")
    .attr("x", 12)
    .attr("dy", "1.2em")
    .attr("text-anchor", "left")
    .text(function(d) { return d.sharedLabel; })
    .style("fill", "#000000");


bar.append("rect")
    .attr("class", "malebar")
    .attr("height", barWidth-gap)
    .attr("x", 10);



bar.append("svg")
    .attr({
        height: barWidth-gap
    })
    .append("text")
    .attr("class", "up")
    .attr("x", 12)
    .attr("dy", "1.2em")
    .attr("text-anchor", "left")
    .text(function(d) { return d.sharedLabel; })
    .style("fill", "#ffffff");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM