首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在d3.js中以行中心呈现文本

在d3.js中以行中心呈现文本
EN

Stack Overflow用户
提问于 2021-04-05 10:02:48
回答 1查看 209关注 0票数 1

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-04-05 12:14:30

renderTextInCenterOfLine将在一行中间放置一个背景文本:

代码语言:javascript
复制
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');
代码语言:javascript
复制
text {
  font-size: 32px;
}
代码语言:javascript
复制
<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>

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66951276

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档