Draw a curve between two points using the diagonal function in d3 js

I start with d3js and try to make a chart myself. I am trying to draw a curve between two points.

function CreateEdge(nodeId1,nodeId2,edgeLabel)
    {

        var curveData = [ { "x": 190,   "y": 100},  { "x": 260,  "y": 50} ];
        var edge = d3.select("svg").append('g');

        //diagonal function that can draw a curve goes in here

        var curve = edge.append("path")
        .attr("d", diagonal)
        .attr("stroke", "#444")
        .attr("stroke-width", 2)
        .attr("fill", "none");

    }

When I did my research, I found some examples using the diagonal function to draw curves. for example this

Is there a way to use the diagonal to draw a simple curve between two known points? Or are there alternative methods?

+5
source share
1 answer

You can do this:

var curveData = [{ x: 190, y: 100 }, { x: 360, y: 150 }];
var edge = d3.select('svg').append('g');
var diagonal = d3.svg.diagonal()
  .source(function (d) { return { x: d[0].y, y: d[0].x }; })            
  .target(function (d) { return { x: d[1].y, y: d[1].x }; })
  .projection(function (d) { return [d.y, d.x]; });
   
d3.select('g')
  .datum(curveData)
  .append('path')
  .attr('class', 'link')
  .attr('d', diagonal)
  .attr('stroke', '#444')
  .attr('stroke-width', 2)
  .attr('fill', 'none');
<!DOCTYPE html>
<html>
  <head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.5.12/d3.js"></script>
  </head>
  <body>
    <svg width=500 height=500></svg>
  </body>
</html>
Run code
+7
source

Source: https://habr.com/ru/post/1622455/


All Articles