d3 v4 - multiple chart zoom sync problem

1,435 views
Skip to first unread message

Andy

unread,
Jul 26, 2016, 10:08:46 AM7/26/16
to d3-js
Hi,

Hope someone can help :)

Using v3 I linked 2 charts with a single zoom behaviour, with no issues - I could drag and zoom happily. However on update to v4 I can't for the life of me get it working as it used to. (probably missing something obvious...!)

The issue seems to be with using d3.event.transform on the transform attribute. If I use mouse to zoom / drag in e.g chart1, chart2 does zoom / drag in sync, however, if I then cross to chart2 and zoom / drag, both charts "reset" to what chart2 was previously.

Below is an example of the code I use. 

And I created a fiddle which hopefully explains the issue. 


Cheers!

var zoom = d3.zoom().scaleExtent([.5, 10]);

var
svg = d3.selectAll('svg'); // 2 charts

var layers = svg.selectAll('g.layer');

function zoomed() {
   
    layers.attr('transform', d3.event.transform);
}

svg.call(zoom);

zoom.on('zoom', zoomed);

Mike Bostock

unread,
Jul 26, 2016, 4:25:42 PM7/26/16
to d3-js
You’ll want to call zoom.transform on the other chart to set its zoom transform to the same transform as the current chart, d3.event.transform.

https://github.com/d3/d3-zoom#zoom_transform

You’ll probably also want to use d3.event.sourceEvent to break the loop, since calling zoom.transform will emit another zoom event, and trigger your zoom event listener again. If d3.event.sourceEvent.type is "zoom", then don’t call zoom.transform again.

Mike

--
You received this message because you are subscribed to the Google Groups "d3-js" group.
To unsubscribe from this group and stop receiving emails from it, send an email to d3-js+un...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Andy

unread,
Jul 26, 2016, 5:38:52 PM7/26/16
to d3-js, mi...@ocks.org
Ah brilliant! I had tried using zoom.transform, but couldn't get it working - must've caught myself in that loop. 

Thanks for the help! (and thanks for the astonishing amount of work you put into d3 :-)

Have updated the Fiddle for anyone else that faces this issue.

Cheers

Andy

guoqing chen

unread,
May 30, 2023, 7:10:00 PM5/30/23
to d3-js
Hi, 
I was trying the code and one error was caught as below, from  line 38 in the Fiddle code:

Uncaught TypeError: Cannot read properties of undefined (reading 'sourceEvent')
    at SVGSVGElement.zoomed (V3_3005_zoom 2 plots_try3.html:181:16)
    at Rt.call (d3.v7.min.js:2:15695)
    at M.emit (d3.v7.min.js:2:278407)
    at M.zoom (d3.v7.min.js:2:278249)
    at SVGSVGElement.T (d3.v7.min.js:2:274243)
    at SVGSVGElement.<anonymous> (d3.v7.min.js:2:20668)

Reply all
Reply to author
Forward
0 new messages