Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Draw curve between two points using diagonal function in d3 js

Tags:

d3.js

I'm starting with d3js and trying to make a graph on my own. I'm 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 diagonal function to draw curves. like this

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

like image 625
Sooraj Avatar asked Jan 01 '16 18:01

Sooraj


1 Answers

You can do like 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>
like image 171
Cyril Cherian Avatar answered Oct 26 '22 23:10

Cyril Cherian