因此,我们在矩形中有两个文本元素。第一个文本元素是类似于圆圈的字体图标,第二个是文本。现在,我们要在矩形的CENTER中对齐它,以使圆首先出现,然后是文本(如项目符号点)。但是在这种情况下我们该怎么做
percentageEntering
.append('svg:rect')
.style('fill', '#F3F3F4')
.attr('width', width)
.attr('height', height);
percentageEntering
.append('svg:text')
.attr('x', width / 2)
.attr('y', height / 2)
.attr('dy', '0.35em')
.attr('text-anchor', 'middle')
.attr('font-family', 'Material Icons')
.style('font-size', '20px')
.style('fill', d => this.subBreadcrumbPercentageColors[d.depth])
.text('some_icon');
percentageEntering
.append('svg:text')
.attr('x', width / 2)
.attr('y', height / 2)
.attr('dy', '0.35em')
.attr('text-anchor', 'middle')
.style('font-size', d => {
const size = ((legendData.length - 2) > 0)
? 12 - (legendData.length - 2)
: 12;
return `${size}px`;
})
.text(d => {
return d.quantity + ' - ' + d.name + ((nodeArray.length === 3) ? ' %' : '');
});
编辑 在@Gerardo提出更改之后,输出如下。所以首先我必须添加
.style('font-family', "'open sans'")
要使文本不使用图标字体,还应使用图标字体(例如:-some_icon
代表图标)。那么,如何确保这些样式不会溢出到孩子身上呢?并且注意到文本不是垂直居中,为此,当我添加一个y
参数时,图标和文本就会重叠。
答案 0 :(得分:2)
针对您的情况,最简单的解决方法是将第二个<text>
元素附加为<tspan>
。像这样:
percentageEntering
.append('text')
.attr('x', width / 2)
.attr('y', height / 2)
.attr('dy', '0.35em')
.attr('text-anchor', 'middle')
.attr('font-family', 'Material Icons')
.style('font-size', '20px')
.style('fill', d => this.subBreadcrumbPercentageColors[d.depth])
.text('some_icon')
.append('tspan')
.style('font-size', d => {
const size = ((legendData.length - 2) > 0) ? 12 - (legendData.length - 2) : 12;
return `${size}px`;
})
.text(d => {
return d.quantity + ' - ' + d.name + ((nodeArray.length === 3) ? ' %' : '');
});
自从您将text-anchor
应用于父文本以来,所有内容(即<text>
元素及其<tspan>
子元素)都应位于中间。
这是一个演示:
const x = 50,
y = 20,
width = 150,
height = 50;
const svg = d3.select("svg")
const rect = svg.append("rect")
.attr("x", x)
.attr("y", y)
.attr("width", width)
.attr("height", height)
.style("fill", "wheat")
.style("border", "gray");
const text = svg.append("text")
.attr('x', x + width / 2)
.attr('y', y + height / 2)
.attr('dy', '0.35em')
.attr('text-anchor', 'middle')
.attr('font-family', 'Material Icons')
.style('font-size', '20px')
.style('fill', "red")
.text('\u25CF')
.append('tspan')
.style('fill', "darkslategray")
.text(" foo bar baz");
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<svg></svg>