每次重绘后设置缩放

时间:2017-06-12 21:24:03

标签: d3.js dagre-d3

我正在使用'dagre d3'来显示依赖图。我还使用了滑块(当用户滑动滑块时,我用它来显示图形的逐步演变),因此每次移动滑块时,都会重新绘制图形。第一次,“缩放”功能将设置如下:

var zoom = d3.behavior.zoom().on("zoom", function () {
inner.attr("transform", "translate(" + d3.event.translate + ")" +
    "scale(" + d3.event.scale + ")");
});
svg.call(zoom);

如果用户放大或缩小图形然后移动滑块,我想保留缩放级别。所以让它工作,我做了以下。 只要用户滑动滑块,就会调用此方法。

function redrawGraphToStage(stageToRedraw) {
    // Not sure how to get previous values. below one works but feel its bit hacky. 
    if(inner[0][0].transform.animVal.length){
        tempInnerTranslate = [inner[0][0].transform.animVal[0].matrix.e, inner[0][0].transform.animVal[0].matrix.f];
        tempInnerScale = inner[0][0].transform.animVal[1].matrix.a;
}
// do modifications to graph. and re-render. 
if(tempInnerScale || tempInnerTranslate){
    //  this will set up the zoom level to before.
    zoom.translate(tempInnerTranslate).scaleExtent(tempInnerScale, tempInnerScale).event(svg);        
}

即使将缩放级别设置为以前的值,我也无法在此之后进行缩放。任何建议都会很棒。

1 个答案:

答案 0 :(得分:0)

试试,

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

function zoomed() {
    inner.attr("transform",
        "translate(" + zoom.translate() + ")" +
        "scale(" + zoom.scale() + ")"
    );
}

function redrawGraphToStage(stageToRedraw) {
    // Not sure how to get previous values. below one works but feel its bit hacky. 
    if(inner[0][0].transform.animVal.length){
        tempInnerTranslate = [inner[0][0].transform.animVal[0].matrix.e, inner[0][0].transform.animVal[0].matrix.f];
        tempInnerScale = inner[0][0].transform.animVal[1].matrix.a;
}
// do modifications to graph. and re-render. 
if(tempInnerScale || tempInnerTranslate){
    //  this will set up the zoom level to before.
    zoom.translate(tempInnerTranslate).scale(tempInnerScale, tempInnerScale);
    zoomed();        
}

我不确定你使用的滑块是什么,但我做了一个演示,你可以用滑杆控制缩放比例。 重大更改: scaleIntent已替换为scale

JSFiddle working demo