relation.json:
{ "nodes":[ { "name": "云天河" , "image" : "SilenceImage/tianhe.jpg" }, { "name": "韩菱纱" , "image" : "SilenceImage/lingsha.jpg" }, { "name": "柳梦璃" , "image" : "SilenceImage/mengli.jpg" }, { "name": "慕容紫英" , "image" : "SilenceImage/ziying.jpg" } ], "edges":[ { "source": 0 , "target": 1 , "relation":"挚友" }, { "source": 0 , "target": 2 , "relation":"挚友" }, { "source": 0 , "target": 3 , "relation":"挚友" } ] }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>力学图加人物关系图</title> </head> <style> .nodetext { font-size: 12px ; font-family: SimSun; fill: #ff3451; } .linetext { font-size: 12px ; font-family: SimSun; fill: #64ffae; fill-opacity:1.0; } </style> <body> <script src="d3.js"></script> <script src="js/relation.js"></script> </body> </html>
var width = 600, height = 600; var img_w = 77, img_h = 90; var svg = d3.select("body").append("svg") .attr("width",width) .attr("height",height) d3.json("relation.json",function(error,root){ if (error) {return console.log(error)} console.log(root); //定义力学图的布局 var force = d3.layout.force() .nodes(root.nodes) .links(root.edges) .size([width,height]) .linkDistance(200) .charge(-1500) .start(); //绘制连接线 var edges_line = svg.selectAll("line") .data(root.edges) .enter() .append("line") .style("stroke","#ccc") .style("stroke_width",1) var edges_text = svg.selectAll(".linetext") .data(root.edges) .enter() .append("text") .attr("class","linetext") .text(function(d){return d.relation;}) //绘制结点 var node_img = svg.selectAll("image") .data(root.nodes) .enter() .append("image") .attr("width",img_w) .attr("height",img_h) .attr("xlink:href",function(d){return d.image}) .on("dblclick",function(d,i){ d.fixed = false; }) .call(force.drag) var node_dx = -20, node_dy = 20; var node_text = svg.selectAll(".nodetext") .data(root.nodes) .enter() .append("text") .attr("class","nodetext") .attr("dx",node_dx) .attr("dy",node_dy) .text(function(d){return d.name}) //运动刷新 force.on("tick",function(){ //限制结点的边界 root.nodes.forEach(function (d,i) { d.x = d.x-img_w/2<0?img_w: d.x; d.x = d.x+img_w/2>width?width-img_w/2: d.x; d.y = d.y - img_h/2<0?img_h/2: d.y; d.y = d.y +img_h/2>height?height-img_h/2: d.y; }) //刷新连接线的位置 edges_line.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;}) //刷新连接线上的文字位置 edges_text.attr("x",function(d){return (d.source.x+ d.target.x)/2;}) .attr("y",function(d){return (d.source.y + d.target.y)/2;}); //刷新结点图片位置 node_img.attr("x",function(d){return d.x-img_w/2;}) .attr("y",function(d){return d.y-img_h/2}) //刷新结点图片位置 node_text.attr("x",function(d){return d.x}) .attr("y",function(d){return d.y+img_w/2}) }) //拖拽开始后设定被拖拽对象为固定 var drag = force.drag() .on("dragstart", function (d) { d.fixed = true; }) })