1. 程式人生 > >d3畫力導向圖

d3畫力導向圖

var width = 600; var height = 600; var svg = d3.select("body") .append("svg") .style("background-color","yellow") .attr("width",width) .attr("height",height) var nodes = [ { name : "0"
}, { name : "1"}, { name : "2"}, { name : "3"}, { name : "4"}, { name : "5"}, { name : "6"}, { name : "7"}, ] var edges = [ { source : 0, target : 1 },{ source : 0
, target : 2 },{ source : 0, target : 3 },{ source : 1, target : 4 },{ source : 1, target : 5 },{ source : 1, target : 6
},{ source : 1, target : 7 } ] //轉換資料 var force = d3.layout.force() .nodes(nodes) .links(edges) .size([width,height]) .linkDistance(90) .charge(-400); force.start(); console.log(nodes); console.log(edges); // var drag = force.drag() // .on("dragstart",function(d){ // d.fixed = false; // }) // .on("dragend",function(d,i){ // d3.select(this).style("fill",color(i)); // }) // .on("drag",function(d){ // d3.select(this).style("fill","yellow"); // }) //轉換資料 var color = d3.scale.category20(); //繪製連線 var lines = svg.selectAll(".forceLine") .data(edges) .enter() .append("line") .attr("class","forceLine") .attr("stroke","black") //繪製節點 var circles = svg.selectAll(".forceCircle") .data(nodes) .enter() .append("circle") .attr("class","forceCircle") .attr("r",20) .style("fill",function(d,i){ return color(i); }) .call(force.drag); //繪製文字 var texts = svg.selectAll(".forceText") .data(nodes) .enter() .append("text") .attr("class","forceText") .attr("x",function(d){ return d.x; }) .attr("y",function(d){ return d.y; }) .attr("dy",".3em") .text(function(d){ return d.name; }) //tick事件的監聽器 force.on("tick",function(){ //更新連線的端點座標 lines.attr("x1",function(d){ return d.source.x; }) lines.attr("y1",function(d){ return d.source.y; }) lines.attr("x2",function(d){ return d.target.x; }) lines.attr("y2",function(d){ return d.target.y; }) //更新節點座標 circles.attr("cx",function(d){ return d.x; }) circles.attr("cy",function(d){ return d.y; }) //更新文位元組點座標 texts.attr("x",function(d){ return d.x; }) texts.attr("y",function(d){ return d.y; }) })