Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I specify the initial zoom level in D3?

Tags:

d3.js

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 + ")");
};
like image 956
Jerry Neumann Avatar asked Dec 30 '11 16:12

Jerry Neumann


2 Answers

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);
like image 84
Jason Davies Avatar answered Oct 15 '22 22:10

Jason Davies


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.

like image 27
makeasy Avatar answered Oct 16 '22 00:10

makeasy