如何使节点中的文本居中? [英] How can I center the text in a node?

查看:35
本文介绍了如何使节点中的文本居中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习 d3.js 和力的系统.我有一个拦截器,因为我无法添加文本并且它完全在圆圈内居中.我曾尝试创建 但它不起作用.我怎样才能实现它?

I'm learning about d3.js and the system of forces. I have a blocker because I am not able to add a text and it is perfectly centered within the circle. I had tried to create <text> but it does not work. How can I achieve it?

在这篇文章中,我尝试创建一个文本元素,但它不起作用.

In this piece I tried to create a text element but it does not work.

    var node = g.append("g")
        .attr("class", "nodes")
        .selectAll("circle")
        .data(graph.nodes)
        .enter()
        .append("circle")
        .attr("r", 20)
        .attr("fill", function(d){
          return colorNode(d.group);
        })
        .style("stroke", function(d){
          return colorNode(d.group);
        })

更新我知道我必须以某种方式在 g 元素中制作它,这个内容是圆圈和文本,但我无法让它工作.显然,我也不知道如何将圆圈内的文本居中.我的结果是圆圈出现在力图之外.我试过这个,但没有用:

UPDATE I know that I must somehow make that within a g element, this content the circle and a text, but I can not make it work. obviously, I also do not know how to center the text inside the circle. My result is that the circle appears outside the force diagram. I have tried this, but not works:

    var node = g.append("g")
        .attr("class", "nodes")
        .selectAll("g")
        .data(graph.nodes)
        .enter()
        .append("g");
        node.append("circle")
        .attr("r", 20)
        .attr("fill", function(d){
          return colorNode(d.group);
        })
        .style("stroke", function(d){
          return colorNode(d.group);
        })

这是我的完整代码:

https://plnkr.co/edit/JhjhFKQgKVtmYQXmgbzF?p=preview

推荐答案

所有你需要的是将 dominant-baseline 设置为 central,它使文本垂直居中,并且text-anchormiddle,使文本水平居中.另外,去掉那些 xy 属性.

All you need is setting the dominant-baseline to central, which centers the text vertically, and text-anchor to middle, which centers the text horizontally. Also, get rid of those x and y attributes.

这应该是选择:

var text = g.append("g")
    .attr("class", "labels")
    .selectAll("text")
    .data(graph.nodes)
    .enter()
    .append("text")
    .style("dominant-baseline", "central")
    .style("text-anchor", "middle")
    .style("font-family", "sans-serif")
    .style("font-size", "0.7em")
    .text(function(d) {
        return d.lotid;
    });

以下是包含这些更改的代码:

Here is your code with those changes:

<!DOCTYPE html>
<meta charset="utf-8">
<style>
  .node {
    stroke: #fff;
    stroke-width: 1.5px;
  }
  
  .link {
    stroke: #999;
    stroke-opacity: .9;
  }
</style>

<body>
  <div id="grafica_back" style="width:100wh"></div>
  <script src="https://d3js.org/d3.v4.min.js"></script>
  <script>
    var w = window,
      d = document,
      e = d.documentElement,
      g = d.getElementsByTagName('body')[0],
      width = w.innerWidth || e.clientWidth || g.clientWidth,
      height = w.innerHeight || e.clientHeight || g.clientHeight;

    var colorNode = d3.scaleOrdinal()
      .range(d3.schemeCategory20),
      colorLink = d3.scaleOrdinal()
      .range(d3.schemeCategory10)

    var svg = d3.select("#grafica_back").append("svg")
      .attr("width", width)
      .attr("height", height);

    var graph = {
      "nodes": [{
          "id": "18362286",
          "lotid": "TEST",
          "epoch": 1511295513000,
          "group": 1,
          "sourceOnly": true
        },
        {
          "id": "18362287",
          "lotid": "TEST",
          "epoch": 1511324313000,
          "group": 2,
          "sourceOnly": false
        }
      ],
      "links": [{
        "source": "18362286",
        "target": "18362287",
        "reltype": "GENEALOGY"
      }]
    };

    var width = 400,
      height = 200;

    var simulation = d3.forceSimulation()
      .nodes(graph.nodes);

    simulation
      .force("charge_force", d3.forceManyBody().strength(-100))
      .force("center_force", d3.forceCenter(width / 2, height / 2))
      .force("links", d3.forceLink(graph.links).id(function(d) {
        return d.id;
      }).distance(100).strength(0.1))
      .force("collide", d3.forceCollide().radius(2))

    ;

    simulation
      .on("tick", ticked);

    //add encompassing group for the zoom 
    var g = svg.append("g")
      .attr("class", "everything");

    //Create deffinition for the arrow markers showing relationship directions
    g.append("defs").append("marker")
      .attr("id", "arrow")
      .attr("viewBox", "0 -5 10 10")
      .attr("refX", 23)
      .attr("refY", 0)
      .attr("markerWidth", 8)
      .attr("markerHeight", 8)
      .attr("orient", "auto")
      .append("svg:path")
      .attr("d", "M0,-5L10,0L0,5");





    var link = g.append("g")
      .attr("class", "links")
      .selectAll("line")
      .data(graph.links)
      .enter().append("line")
      .attr("stroke", function(d) {
        console.log(d);
        return colorLink(d.group);
      })
      .attr("marker-end", "url(#arrow)");

    var node = g.append("g")
      .attr("class", "nodes")
      .selectAll("circle")
      .data(graph.nodes)
      .enter()
      .append("circle")
      .attr("r", 20)
      .attr("fill", function(d) {
        return colorNode(d.group);
      })
      .style("stroke", function(d) {
        return colorNode(d.group);
      })


    //add drag capabili



    var drag_handler = d3.drag()
      .on("start", drag_start)
      .on("drag", drag_drag)
      .on("end", drag_end);

    drag_handler(node);

    var text = g.append("g")
      .attr("class", "labels")
      .selectAll("text")
      .data(graph.nodes)
      .enter()
      .append("text")
      .style("dominant-baseline", "central")
      .style("text-anchor", "middle")
      .style("font-family", "sans-serif")
      .style("font-size", "0.7em")
      .text(function(d) {
        return d.lotid;
      });

    node.on("click", function(d) {
      d3.event.stopImmediatePropagation();
      self.onNodeClicked.emit(d.id);
    });

    node.append("title")
      .text(function(d) {
        d.lotid;
      });

    //add zoom capabilities 
    var zoom_handler = d3.zoom()
      .on("zoom", zoom_actions);

    zoom_handler(svg);

    //Drag functions 
    //d is the node 
    function drag_start(d) {
      if (!d3.event.active) simulation.alphaTarget(0.3).restart();
      d.fx = d.x;
      d.fy = d.y;
    }

    //make sure you can't drag the circle outside the box
    function drag_drag(d) {
      d.fx = d3.event.x;
      d.fy = d3.event.y;
    }

    function drag_end(d) {
      if (!d3.event.active) simulation.alphaTarget(0);
      d.fx = null;
      d.fy = null;
    }

    //Zoom functions 
    function zoom_actions() {
      g.attr("transform", d3.event.transform)
    }

    function ticked() {
      //update circle positions each tick of the simulation 
      node
        .attr("cx", function(d) {
          return d.x;
        })
        .attr("cy", function(d) {
          return d.y;
        });

      //update link positions 
      link
        .attr("x1", function(d) {
          return d.source.x;
        })
        .attr("y1", function(d) {
          return d.source.y;
        })
        .attr("x2", function(d) {
          return d.target.x;
        })
        .attr("y2", function(d) {
          return d.target.y;
        });

      text
        .attr("transform", function(d) {
          return "translate(" + d.x + "," + d.y + ")";
        });
    }
  </script>

这篇关于如何使节点中的文本居中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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