如何在D3中为同一文本设置不同的颜色?

问题描述 投票:0回答:1

我使用D3在线上有一些文字。出于某种原因,我需要文本的某些部分具有不同的颜色,例如,我可能有黑色文本,然后是红色文本,如下所示:“黑色(红色)”。做这个的最好方式是什么? 我可以在一个文本中使用不同的颜色吗? 如果我必须为第二种颜色绘制另一个文本,我如何将它附加到第一个文本元素?

这是我生成文本的方式:

       var texts = lines.append("svg:text")
        .text(function (d) {
            return d.label;
        })
        .attr("class", "link-label")
        .attr("text-anchor", "middle")
d3.js svg
1个回答
1
投票

除非你想处理<defs>和渐变,否则你不能将两个或更多fill属性设置为相同的<text>

最简单的解决方案是打破你的文本,并附加另一种风格的<tspan>。如何打破文本是一个问题,取决于您在问题中未指定的确切目标。在下面的演示中,我使用连字符来打破文本。

这里是:

var svg = d3.select("svg");
var data = ["This is some text - with different colours",
  "This is another text - with different colours",
  "This is the last text - and the colours are still different"
];

var text = svg.selectAll(null)
  .data(data)
  .enter()
  .append("text")
  .attr("y", function(d, i) {
    return 40 + i * 40
  })
  .text(function(d) {
    return d.split("-")[0]
  })
  .append("tspan")
  .style("fill", "red")
  .text(function(d) {
    return d.split("-")[1]
  })
<script src="https://d3js.org/d3.v4.min.js"></script>
<svg width="400"></svg>
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.