使用将文字放在圆圈中间.d3.js [英] Put text in the middle of a circle using. d3.js

查看:88
本文介绍了使用将文字放在圆圈中间.d3.js的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一段在其中绘制圆的代码,我需要在每个圆内放置一个文本,我还想知道如何为圆的每个元素加上一定的大小.非常感谢.

I have this piece of code in which circles are drawn, I need to put a text inside each circle, I would also like to know how I can put a certain size to each of the elements of the circle. Thank you very much.

  svg = d3.select(selector)
    .append('svg')
    .attr('width', width)
    .attr('height', height);

  // Bind nodes data to what will become DOM elements to represent them.
  bubbles = svg.selectAll('.bubble')
    .data(nodes, function (d) { return d.id; });

  // Create new circle elements each with class `bubble`.
  // There will be one circle.bubble for each object in the nodes array.
  // Initially, their radius (r attribute) will be 0.



  bubbles.enter().append('circle')
    .classed('bubble', true)
    .attr('r', 0)
    .attr('fill', function (d) {  return  fillColor(d.group); })
    .attr('stroke', function (d) { return d3.rgb(fillColor(d.group)).darker(); })
    .attr('stroke-width', 2)
    .on('mouseover', showDetail)
    .on('mouseout', hideDetail);


  // Fancy transition to make bubbles appear, ending with the
  // correct radius
  bubbles.transition()
    .duration(2000)
    .attr('r', function (d) { return d.radius; });

推荐答案

一种好的做法是为每个气泡创建一个组元素,因为它们将由两个元素(一个圆和一个文本)组成.

A good practice would be to create a group element for each bubble because they will be composed of two elements - a circle and text.

// Bind nodes data to what will become DOM elements to represent them.
bubbles = svg.selectAll('.bubble')
  .data(nodes, function(d) {
    return d.id;
  })
  .enter()
  .append('g')
  .attr("transform", d => `translate(${d.x}, ${d.y})`)
  .classed('bubble', true)
  .on('mouseover', showDetail)
  .on('mouseout', hideDetail)

此后,可以添加圆圈和文字:

After that, circles and texts can be appended:

circles = bubbles.append('circle')
  .attr('r', 0)
  .attr('stroke-width', 2)


texts = bubbles.append('text')
  .attr('text-anchor', 'middle')
  .attr('alignment-baseline', 'middle')
  .style('font-size', d => d.radius * 0.4 + 'px')
  .attr('fill-opacity', 0)
  .attr('fill', 'white')
  .text(d => d.text)

// Fancy transition to make bubbles appear, ending with the
// correct radius
circles.transition()
  .duration(2000)
  .attr('r', function(d) {
    return d.radius;
  });

对于隐藏/显示文本,可以使用 fill-opacity 属性,并在应隐藏文本时将其设置为0,而应将其显示为1:

For hiding/showing text, you can use fill-opacity attribute and set it 0 when the text should be hidden, and 1 if it should be shown:

function showDetail(d, i) {
  d3.select(this.childNodes[1]).attr('fill-opacity', 1)
}

function hideDetail(d, i) {
  d3.select(this.childNodes[1]).attr('fill-opacity', 0)
}

示例: https://jsfiddle.net/r880wm24/

这篇关于使用将文字放在圆圈中间.d3.js的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆