Done :
node.attr("transform", function(d) {
//Here i create a node radius so it doesnt go offscreen
var nodeRadius = d.weight * 2 + 12
//here I do checks to see if it goes offscreen
if(d.x<= nodeRadius){
d.x = nodeRadius;
}
if(d.y<= nodeRadius){
d.y = nodeRadius;
}7
if(d.x>width - nodeRadius){
d.x = width - nodeRadius;
}
if(d.y>height - nodeRadius){
d.y = height - nodeRadius;
}
return "translate(" + d.x + "," + d.y + ")";
});
This is done in the tick function
, so it checks every frame. I created an actual tick function so it's reusable. Please check my changes in your JSFiddle as I've made quite a few. But everything seems to work fine.
Updated fiddle : http://jsfiddle.net/aVhd8/177/
If you want to move the nodes before it starts then the boundary has to remember that movement :
node.attr("transform", function(d) {
//Here i create a node radius so it doesnt go offscreen
var nodeRadius = d.weight * 2 + 12
//here I do checks to see if it goes offscreen
if(d.x<= nodeRadius-movement){ //have to take movement away as you have moved the nodes/links previously
d.x = nodeRadius-movement;
}
if(d.y<= nodeRadius){
d.y = nodeRadius;
}
if(d.x>width - nodeRadius-movement){
d.x = width - nodeRadius-movement;
}
if(d.y>height - nodeRadius){
d.y = height - nodeRadius;
}
return "translate(" + d.x + "," + d.y + ")";
});
Notice here I have took movement
into account. You also need to do the same for the links:
JSFiddle : http://jsfiddle.net/aVhd8/180/