javascript - D3js force layout - line with gradient between nodes -


this d3 force layout: (please run code snippet)

var width = 600,      height = 600;    var svg = d3.select('body').append('svg')      .attr('width', width)      .attr('height', height);    var color = d3.scale.category20();    var datanodes = [      { x:   width/3, y:   height/3 , group: 0, color: 'blue'},      { x: 2*width/3, y:   height/3, group: 1, color: 'red' },      { x:   width/2, y: 2*height/3, group: 2, color: 'green'}  ];    var datalinks = [    { source: 0, target: 1},    { source: 1, target: 2},    { source: 2, target: 0}  ];    var force = d3.layout.force()      .charge(-400)      .linkdistance(height/2)      .size([width, height])      .linkstrength(1.3)      .friction(0.8)      .gravity(0.9);    force      .nodes(datanodes)      .links(datalinks)      .start();    var link = svg.selectall(".link")        .data(datalinks)      .enter().append("line")        .attr("class", "link");    var node = svg.selectall(".node")      .data(datanodes)    .enter().append("circle")      .attr("class", function(d){ return "node " + d.color})      .attr("r", width/20)      .call(force.drag);    node.append("title")        .text(function(d) { return d.color; });      force.on('tick', function() {      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; });        node.attr("cx", function(d) { return d.x; })          .attr("cy", function(d) { return d.y; });  });
.node {      fill: #ccc;      stroke: #fff;      stroke-width: 0;  }  .node.blue {      fill: blue;  }  .node.red {      fill: red;  }  .node.green {      fill: green;  }    .link {      fill: none;               stroke: black;      stroke-width: 20px;  }
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>

this want achieve: enter image description here

how possible ? how can apply gradient on links between nodes ? if not clear please ask.

thanks !

you can , create gradient , pass gradient id:

var link = svg.selectall(".link")       .data(datalinks)     .enter().append("line")       .attr("class", "link")       .style("stroke",function(d){           var id = "s"+d.source.index +"t" + d.target.index;           var gradient1 = defs.append("lineargradient").attr("id",  id);           gradient1.append("stop").attr("offset", "0%").attr("stop-color", d.target.color);           gradient1.append("stop").attr("offset", "100%").attr("stop-color", d.source.color);           return "url(#" + id + ")";       }); 

working code here

hope helps!


Comments

Popular posts from this blog

sublimetext3 - what keyboard shortcut is to comment/uncomment for this script tag in sublime -

java - No use of nillable="0" in SOAP Webservice -

ubuntu - Laravel 5.2 quickstart guide gives Not Found Error -