12

I have written a script to graphically display some row-oriented data, with bars, labels and connections between rows. As the dataset has grown, the resulting SVG element has exceeded the size of the screen. To keep the result on one screen (partly to make the d3 zoom behavior easier for the user to manage), I have scaled the SVG element before drawing so that it will fit the screen. I did this by appending a transform/scale attribute to the SVG element.

The problem is, d3's behavior.zoom does not know about this change in scale, so when I start to zoom, it first resets the scale to 1. Is there a way to change the initial scale in d3's behavior.zoom?


EDIT: added a work-around

Kludged this by multiplying d3.event.scale by the initial scale in the redraw() function. So, initial declaration of SVG element is

var SVG = d3.select('#timeline')
    .append('svg:svg')
        .attr('class','chart')
        .attr('transform','scale('+bscale+')')
        .attr('width', wwidth)
        .attr('height', wheight)
        .call(d3.behavior.zoom()
            .extent([[0,Infinity],[0,Infinity],[0,Infinity]])
            .on('zoom', redraw));

and

function redraw() {
    SVG.attr("transform",
        "translate(" + d3.event.translate + ")"
        + "scale(" + d3.event.scale * bscale + ")");
};
Jerry Neumann
  • 415
  • 1
  • 4
  • 11

3 Answers3

13

As of D3 2.8.0, the new d3.behavior.zoom allows you to set the current scale, e.g.

d3.behavior.zoom()
    .scale(currentScale);
Jason Davies
  • 4,693
  • 30
  • 39
  • Unfortunately, the d3 API [ https://github.com/mbostock/d3/wiki/API-Reference ] doesn't have a page for this. Is there an example online that shows zoom() in use? – August May 13 '12 at 14:13
  • 8
    what should `currentScale` be? – vsync Jan 24 '16 at 17:43
3

In d3 v4, you can use:

svg.call(zoom.transform, d3.zoomIdentity.scale(X_SCALE,Y_SCALE));

Simple example:

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

var zoomer = svg.append("rect")
        .call(zoom)
        .call(zoom.transform, d3.zoomIdentity.scale(2,2));

function zoomed() {
        svg.attr("transform", d3.event.transform);
    }

Hope that helps.

makeasy
  • 907
  • 1
  • 6
  • 15
0

After setting the zoom value, you have to call the zoom event to make the changes appear on the screen. Here's how you do it:

//set the min and max extent to which zooming can occur and define a mouse zoom function
var zoom = d3.behavior.zoom().scaleExtent([0.3, 3]).on("zoom", zoomed);
zoom.translate([50,50]).scale(2);//translate and scale to whatever value you wish
zoom.event(yourSVGlayer.transition().duration(50));//does a zoom
//this function handles the zoom behaviour when you zoom with the mouse
function zoomed() { yourSVGlayer.attr("transform", "translate("+d3.event.translate+")scale(" + d3.event.scale + ")"); }
Nav
  • 19,885
  • 27
  • 92
  • 135