Search code examples
javascriptd3.jssynchronizationzooming

D3 V5 : sync initial zoom with zoom event


I'm trying to set an initial zoom on my network. It works fine, but as soon as I try to manually zoom on the graph, the visualisation jumps to it's natural zoom settings. Reading answers on Stack and the official documentation of d3, the following code looks right to me, but it doesn't solve the issue.

What am I doing wrong? Many thanks for your help!

const svg = d3.select('div#network')
    .append("svg")
        .attr("width", width + margin.left + margin.right)
        .attr("height", height + margin.top + margin.bottom)
        .call(d3.zoom().on("zoom", function () {
            svg.attr("transform", d3.event.transform)
        }),d3.zoomIdentity.scale(.2))
    .append("g")
        .attr("transform", `translate(${margin.left},${margin.top})`)
        .attr("transform","scale(.2)")

Solution

  • Solved! I was almost right! You need to make a second "call" instead of giving this transform as a parameter of the first one.

    const svg = d3.select('div#reseau')
        .append("svg")
            .attr("width", width + margin.left + margin.right)
            .attr("height", height + margin.top + margin.bottom)
            .call(d3.zoom().on("zoom", function () {
                svg.attr("transform", d3.event.transform)
            }))
            .call(d3.zoom().transform,d3.zoomIdentity.scale(.2))
        .append("g")
            .attr("transform", `translate(${margin.left},${margin.top})`)
            .attr("transform","scale(.2)")