Unable to Zoom d3 techanjs

310 views Asked by At

I'm using almost same code which has been used in http://techanjs.org/. I was trying to add zooming feature in the chart as the developer has rendered the chart in here. But somehow I'm not able to zoom it. I'm getting error selection is not defined in console. I'm using following code to render the chart. https://paste.fedoraproject.org/paste/7gJq9wKL4h4s862EDuxnQQ. I'm sure I'm doing something wrong in here, I would really appreciate if I get any assistance regarding it as I'm still learning D3.

1

There are 1 answers

3
Fraser On

I'd guess the problem is that you are referencing the variable selection but it isn't defined.

Hence -

selection is not defined

selection is the parameter passed into your bigchart function.

But you then use it in your reset, zoomed functions where it is not defined.

//Zoom Begins
 function reset() {
        zoom.scale(1);
        zoom.translate([0,0]);
        selection.call(draw); // this will throw an error
    }

    function zoomed() {
        x.zoomable().domain(d3.event.transform.rescaleX(zoomableInit).domain());
        y.domain(d3.event.transform.rescaleY(yInit).domain());
        yPercent.domain(d3.event.transform.rescaleY(yPercentInit).domain());

        selection.call(draw); // this will throw an error
    }
//Zoom Ends

To fix, either pass the selection to the functions as a parameter (like the other functions) - or else make the selection a property of BigChart so that it can be referenced by the reset and zoomedfunctions.

i.e.

 // pass selection to the functions as a parameter

 function reset(selection) {
    zoom.scale(1);
    zoom.translate([0,0]);
    selection.call(draw);
 }

 function zoomed(selection) {
    x.zoomable().domain(d3.event.transform.rescaleX(zoomableInit).domain());
    y.domain(d3.event.transform.rescaleY(yInit).domain());
    yPercent.domain(d3.event.transform.rescaleY(yPercentInit).domain());
    selection.call(draw);
 }

Then when you call the functions obviously you pass in the correct object...e.g.

zoom = selection.call(d3.zoom().on("zoom", zoomed));

rather than

zoom = d3.zoom().on("zoom", zoomed),