Stack Exchange
Render text in center of line in d3.js
I am new to d3.js I want to how to render the text in the center of line in d3.js. I have attached the image how it should be rendered.


renderTextInCenterOfLine will put a text with background in the center of a line:


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>



