Last active
April 10, 2019 19:22
-
-
Save MaximPiessen/32ca181307f7aeb756ff5a2ccf30ff9b to your computer and use it in GitHub Desktop.
Adding gradients to edges, excerpt from "function createV4SelectableForceDirectedGraph(svg, graph)"
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ... | |
function getGradID(d){return "linkGrad-" + d.source + "-"+ d.target;} | |
var defs = d3v4.select("svg").append("defs"); | |
var grads = defs.selectAll("linearGradient") | |
.data(graph.links); | |
var lingrads = grads.enter().append("linearGradient"); | |
lingrads.attr("id", getGradID) | |
.attr("gradientUnits", "userSpaceOnUse") | |
//source = red | |
lingrads.append("stop") | |
.attr("offset", "0%") | |
.attr("stop-color", "red") | |
//target = green | |
lingrads.append("stop") | |
.attr("offset", "100%") | |
.attr("stop-color", "green") | |
var link = gDraw.append("g") | |
.attr("class", "links") | |
.selectAll("line") | |
.data(graph.links) | |
.enter().append("line") | |
.attr("stroke-width", function(d) { return Math.sqrt(d.value); }); | |
link.attr("source", function(d){return d.source}) | |
.attr("target", function(d){return d.target}) | |
.style("stroke", function(d){ | |
return "url(#" + getGradID(d) + ")"; | |
}) | |
.attr("class", function(d) { | |
var id1 = d.source.toString(); | |
var id2 = d.target.toString(); | |
if(d.bi_directional){ | |
return "edge link-bi " + id1 + " " + id2; | |
}else{ | |
return "edge link " + id1 + " " + id2; | |
} | |
}) | |
var node = gDraw.append("g") | |
.attr("class", "nodes") | |
.selectAll("circle") | |
.data(graph.nodes) | |
.enter().append("circle") | |
.attr("r", 4) | |
.attr("fill", function(d) { | |
if ('color' in d) | |
return d.color; | |
else | |
return color(d.group); | |
}) | |
.call(d3v4.drag() | |
.on("start", dragstarted) | |
.on("drag", dragged) | |
.on("end", dragended)); | |
node.attr("id", function(d){return d.id}) | |
.attr("class", "node") | |
// ... | |
function ticked() { | |
// update node and line positions at every step of | |
// the force simulation | |
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; }); | |
lingrads.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; }); | |
} | |
// ... |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment