Translate coordinates of label in d3 org chart

10 views Asked by At

How to place a label on the center of the pink path in the example below?

Overwrite refX and refY of the label definition. But then how two translate the center-coords? Because the distance (conn._target.x - conn._source.x)/2; between the nodes is not scaled.

Running code:

const data = [
    { customId: 1, customParentId: null, customName: 'node1' },
    { customId: 2, customParentId: 1, customName: 'node2' },
    { customId: 3, customParentId: 1, customName: 'node3' },
  ];

    chart = new d3.OrgChart()
      .nodeId((dataItem) => dataItem.customId)
      .parentNodeId((dataItem) => dataItem.customParentId)
      .nodeWidth((node) => 100)
      .nodeHeight((node) => 100)
      .defs(myDefs)
      .nodeContent((node) => {
        return `<div customId="${node.data.customId}" 
            style="background-color:aqua;width:${node.width}px;height:${node.height}px"
          > 
               ${node.data.customName}
           </div>`;
      })
      .container('.chart-container')
      .data(data).render();
  function myDefs(state, visibleConnections) {
            return `<defs>
                ${visibleConnections.map(conn => {
                const labelWidth = this.getTextWidth(conn.label, { ctx: state.ctx, fontSize: 2, defaultFont: state.defaultFont });
                const refX = (conn._target.x - conn._source.x)/2;
                const refY = (conn._target.y - conn._source.y)/2;
                return `
                   <marker id="${conn.from + "_" + conn.to}" refX="${refX}" refY="${refY}" markerWidth="500"  markerHeight="500"  orient="${conn._source.x < conn._target.x ? "auto" : "auto-start-reverse"}" >
                   <rect rx=0.5 width=${conn.label ? labelWidth + 3 : 0} height=3 y=1  fill="#E27396"></rect>
                   <text font-size="2px" x=1 fill="white" y=3>${conn.label || ''}</text>
                   </marker>

                   <marker id="arrow-${conn.from + "_" + conn.to}"  markerWidth="500"  markerHeight="500"  refY="2"  refX="1" orient="${conn._source.x < conn._target.x ? "auto" : "auto-start-reverse"}" >
                   <path transform="translate(0)" d='M0,0 V4 L2,2 Z' fill='#E27396' />
                   </marker>
                `}).join("")}
                </defs>
                `}



setTimeout(function() {
  chart.connections([{ from: "1", to: "2", label: "Conflicts of interest" }]).render();
}, 500);
<script src="https://d3js.org/d3.v7.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/build/d3-flextree.js"></script>

<div class="chart-container"></div>

0

There are 0 answers