Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting visible nodes in d3.js force layout after zoom-pan

I use a force directed layout in d3.js once on load to position nodes and edges. Then I can zoom and pan the svg. When I zoom in I want to detect which nodes and edges are visible so I can implement lazy loading of additional data only for the visible nodes and edges.

Does anyone know what is the best way to get the (partialy) visible elements?

Code is below (just pasted some examples together):

var svg = d3.select("#chart")
  .append("svg")
  .attr("width", width)
  .attr("height", height)
  .attr("pointer-events", "all")
  .append('svg:g')
  .call(d3.behavior.zoom().on("zoom", redraw))
  .append('svg:g')

svg.append('svg:rect')
  .attr('width', width)
  .attr('height', height)
  .attr('fill', 'white')

function redraw() {
  trans=d3.event.translate;
  scale=d3.event.scale
  svg.attr("transform", "translate(" + trans + ")" + " scale(" + scale + ")")
  console.log(scale)
}
like image 965
Mr. Avatar asked Oct 22 '22 01:10

Mr.


1 Answers

If you are using scales, you can find the currently visible range using scale.invert. So to find the visible values for an axis where the width is 600px, use x.invert(0) and x.invert(600).

like image 158
sparrowman Avatar answered Oct 30 '22 18:10

sparrowman