Force model using d3.js does not work well

Asked 2 years ago, Updated 2 years ago, 27 views

<!DOCTYPE html>
<html lang="ja">
<style>
US>svg{
	border —solid1px;
	}
	</style>
<head>
  <metacharset="utf-8">
  <title>D3.js (Force Layout) Practice</title>
</head>
<body>
  <script src="http://d3js.org/d3.v3.js" charset="utf-8"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>

  <script>
  varw = 800;
  varh = 800;

  var nodes = [ ];
  var links = [ ];


  function for_each(array, func) {Array.prototype.forEach.call(array, func);}

  function get_html(callback){
  	varhatena_hotentry_url="http://b.hatena.ne.jp/hotentry";
  	hatena_hotentry_url="http://allow-any-origin.appspot.com/"
  		+ encodeURIC component(hatena_hotentry_url);

  	/*// var hatena_hotentry_url="./hatena_hotentry.html"
  */
  	var req = new XMLHttpRequest();
  	req.open("GET", hatena_hotentry_url);
  	req.onreadystatechange=function(){
  		if(req.readyState===4&req.status===200){
  			callback(req.responseText);
  			req = undefined;
  		}
  	};
  	req.send(null);
  }

  function html_to_relationship(html){
  	var doc = new DOMParser().parseFromString(html, "text/html");
  	error_tags=doc.getElementsByTagName("parserror");
  	if(error_tags.length){
  		console.log("error:", error_tags);
  		return [[["Parse error", "Maybe HTML is broken"]];
  	}

  	var relationship=[]; /* // [[["name", ...], ...]
  */ variable_elms=doc.querySelectorAll(
  			"[data-track-section='default'].entry-contents");
  	for_each(entry_elms, function(entry_elm){
  		variable_link_elm=entry_elm.querySelector(".entry-link");
  		if(!entry_link_elm) {return;}

  		var name_array=[];
  		relationship.push(name_array);
  		name_array.push(entry_link_elm.title);

  		variable_meta_elm=entry_elm.nextElementSibling;
  		if(!entry_meta_elm) {return;}
  		for_each(entry_meta_elm.querySelectorAll("a.tag"), function(tag_elm){
  			name_array.push(tag_elm.textContent);
  		});
  	});

  	return relationship;

  	}



  function relationship_view(relationship){
  	/* document.getElementById("view").textContent
  	       	= JSON.stringify (relationship, undefined, 2);
  */




  	for (vari=0;i<relationship.length;i++){
  		if(i+1<relationship.length){
  			var num="{source:"+i+", target:"+(i+1)+"}";
  		} else {
  			var num="{source:"+i+", target:"+0+"}";
  		}
  		var list="{label:"+relationship[i][0]+"}";
  			nodes.push(list);
  			 links.push(num);
  	}




  		var force = d3.layout.force()
          .nodes (nodes)
          .links (links)
          .size([w,h])
          .linkStrength (0.1)
          .friction (0.9)
          .distance (200)
          .charge (-30)
          .gravity (0.1)
          .theta(0.8)
          .alpha(0.1)
          .start();

  		/* console.log(nodes)*/

  		varsvg=d3.select("body").append("svg").attr({width:w,height:h});

  		varlink=svg.selectAll("line")
          .data(links)
          .enter()
          .append("line")
          .style({stroke:"#ccc",
                  "stroke-width":1});


  		var node = svg.selectAll("circle")
  						.data(nodes)
  						.enter()
  						.append ("circle")
  						.attr({r:20,
  								opacity: 0.5})
  						.style({fill:"red")
  						.call(force.drag);


  		var label = svg.selectAll('text')
  				.data(nodes)
  				.enter()
  				.append('text')
  				.attr({"text-anchor": "middle",
  							"fill": "black"})
  				.style({"font-size":11})
  				.text(function(d){return nodes.label;});


  		 force.on("tick", function(){
  		      link.attr({x1:function(d){returnd.source.x;},
  		                 y1: function(d) {return d.source.y;},
  		                 x2 —function(d) {returnd.target.x;},
  		                 y2 —function(d) {return d.target.y;});
  		      node.attr({cx:function(d){return d.x;},
  		                 cy:function(d) {return d.y;});
  		      label.attr({x:function(d){returnd.x;},
  		    	  		  y —function(d) {return d.y});

  })
  }

  get_html(function(html){relationship_view(html_to_relationship(html)));});


  </script>
</body>
</html>

I'm trying to move it with the source like above, but the force model is not drawn well.
I'm using the for statement to create a nodes array and a links array, but isn't it loaded well?
We are currently adding links arrays, but if we erase them and just delete the nodes array, the widgh and height of the svg element will be drawn, but if we add them, they will not even be drawn.

I am referring to two pages (http://qiita.com/tag1216/items/b7f846af66db30b8c393), and (http://bl.ocks.org/mbostock/4062045).
Thank you for your help.

javascript html

2022-09-30 10:13

1 Answers

The definition part of the data seems to be strange.
Nodes and links were shown to contain associative arrays as follows:

for(vari=0;i<relationship.length;i++){
    if(i+1<relationship.length){
        var num = {"source":i, "target":+(i+1)};
    } else {
        var num = {"source":i, "target":0};
    }
    var list = {"label": relationship[i][0]};
            nodes.push(list);
         links.push(num);
}


2022-09-30 10:13

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.