Christian Stewart
Christian Stewart

Reputation: 15519

D3 Zoom in version 3

There are a few examples on Stack Overflow on how to achieve a pan and zoom in a force graph using D3, but they all use D3 Version 2, not the latest Version 3.

For example, here is one solution: http://jsfiddle.net/nrabinowitz/QMKm3/

But, it appears that in Version 3, applying transform="translate(0,0) scale(0.5)" on the core svg view does not seem to work.

Please excuse my coffeescript if you are not familiar with reading it:

height = null
width = null
svg = null

resizeHandler = ->
  height = $("#fcMiddle").height()
  width = $("#fcMiddle").width()
  console.log height+"x"+width
  rerender()

$(window).resize resizeHandler

redraw = ->
  #console.log "here", d3.event.translate, d3.event.scale
  svg.attr "transform", "translate(" + d3.event.translate + ")" + " scale(" + d3.event.scale + ")"

svg = d3.select("#fcMiddle").append("svg").attr("width", width).attr("height", height).attr("pointer-events", "all")

rerender = ->
  $("#fcMiddle svg").empty()
  svg.append('svg:g').call(d3.behavior.zoom().on("zoom", redraw)).append('svg:g').append('svg:rect').attr('width', width).attr('height', height).attr('fill', 'white')
  color = d3.scale.category20()
  force = d3.layout.force().charge(-120).linkDistance(30).size([width, height])
  d3.json "/data/systems.json", (error, graph) ->
    console.log graph
    force.nodes(graph.nodes).links(graph.links).start()
    link = svg.selectAll(".link").data(graph.links).enter().append("line").attr("class", "link").style("stroke-width", (d) ->
      Math.sqrt d.value
    )
    node = svg.selectAll(".node").data(graph.nodes).enter().append("circle").attr("class", "node").attr("r", 5).style("fill", (d) ->
      color d.group
    ).call(force.drag)
    node.append("title").text (d) ->
      d.name

    force.on "tick", ->
      link.attr("x1", (d) ->
        d.source.x
      ).attr("y1", (d) ->
        d.source.y
      ).attr("x2", (d) ->
        d.target.x
      ).attr "y2", (d) ->
        d.target.y

      node.attr("cx", (d) ->
        d.x
      ).attr "cy", (d) ->
        d.y

This is nearly identical to the version in JavaScript here. I redraw everything if the window gets rescaled, and I reuse the by clearing its contents every time I re-draw everything. These things should not affect the transformation for zoom.

Upvotes: 1

Views: 758

Answers (1)

Lars Kotthoff
Lars Kotthoff

Reputation: 109272

When you're applying the transform to an element, make sure that it's not the svg element -- transforming that will have no effect (see here for more information). You can however add a g element at the top level (i.e. everything else is added below that) and transform that.

Upvotes: 1

Related Questions