我是d3.js的新手,我想知道如何在d3.js的行中间呈现文本。我已经附上了应该如何渲染的图像。

发布于 2021-04-05 12:14:30
renderTextInCenterOfLine将在一行中间放置一个背景文本:
const renderTextInCenterOfLine = (line, text) => {
const from = parseInt(line.attr('x1'));
const to = parseInt(line.attr('x2'));
const y = parseInt(line.attr('y1'));
const svg = d3.select('svg');
const textBackground = svg.append('rect')
const textElement = svg.append('text')
.text(text)
.attr('x', (from + to) / 2)
.attr('y', y)
.attr('text-anchor', 'middle')
.attr('alignment-baseline', 'central');
const box = textElement.node().getBBox();
const width = box.width + 50; //
const height = box.height + 20;
textBackground
.attr('x', (from + to - width) / 2)
.attr('y', y - height / 2)
.attr('width', width)
.attr('height', height)
.style('fill', 'white')
}
renderTextInCenterOfLine(d3.select('#my-line'), '2020');text {
font-size: 32px;
}<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<svg width="500" height="100">
<line id="my-line" x1="20" x2="480" y1="40" y2="40" stroke="#000" />
<line x1="20" x2="20" y1="30" y2="50" stroke="#000" />
<line x1="480" x2="480" y1="30" y2="50" stroke="#000" />
</svg>
https://stackoverflow.com/questions/66951276
复制相似问题