2011-12-30 123 views
11

我已经编写了一个脚本来以图形方式显示一些面向行的数据,并在行之间用条形图,标签和连接。随着数据集的增长,所产生的SVG元素已经超过了屏幕的大小。为了将结果保留在一个屏幕上(部分是为了让用户更易于管理d3缩放行为),我在绘制之前缩放了SVG元素,以便它适合屏幕。我通过将一个transform/scale属性附加到SVG元素来完成此操作。如何在D3中指定初始缩放级别?

问题是,d3的行为.zoom不知道缩放比例的变化,所以当我开始缩放时,它首先将缩放比例重置为1.是否有方法来改变d3行为中的缩放比例。 ?


编辑:加入通过在再拉深()函数由初始规模乘以d3.event.scale一个变通

Kludged此。所以,SVG元素的初始声明

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)); 

function redraw() { 
    SVG.attr("transform", 
     "translate(" + d3.event.translate + ")" 
     + "scale(" + d3.event.scale * bscale + ")"); 
}; 

回答

12

由于D3 2.8.0,新d3.behavior.zoom允许您设置目前的规模,例如

d3.behavior.zoom() 
    .scale(currentScale); 
+0

不幸的是,d3 API [https://github.com/mbostock/d3/wiki/API-Reference]没有这个页面。在线是否有示例显示zoom()正在使用? – August 2012-05-13 14:13:26

+0

找到了这个:https://github.com/mbostock/d3/pull/488 – August 2012-05-13 14:14:54

+5

'currentScale'应该是什么? – vsync 2016-01-24 17:43:42

0

设置缩放值后,必须调用缩放事件才能使更改显示在屏幕上。 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 + ")"); } 
2

在D3 V4,您可以使用:

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

简单的例子:

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); 
    } 

希望有所帮助。