简体   繁体   English

d3.js中的简单放大

[英]simple zoom in d3.js

I am trying to implement a simple zoom in d3.js, simpler than all the examples I have gone through (I suppose) but it just doesn't wanna work. 我正在尝试在d3.js中实现一个简单的缩放,它比我经历过的所有示例都要简单(我想),但是它根本不起作用。 So, the functionality that I want to implement is: the user clicks on a section of the graph and that section zooms at a predefined fixed size in the centre of the chart; 因此,我要实现的功能是:用户单击图形的某个部分,然后该部分以图表中心的预定义固定大小缩放; the user cannot zoom it any further, no panning either. 用户无法进一步缩放,也无法平移。 And when the user clicks at any other section of the chart, the zoomed section translates back to its normal/original position. 当用户单击图表的任何其他部分时,缩放的部分将转换回其正常/原始位置。

var container = svg.append("g").classed("container-group", true);
        container.attr({transform: "translate(" + 40*test_data.row + "," + 40*test_data.col + ")"});
        container.call(d3.behavior.zoom().scaleExtent([1,5]).on("zoom", zoom));

function zoom() {
        container.attr("transform","translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")");
    }  

I have tried zoom.translate and zoom.size but couldn't get them right. 我尝试过zoom.translate和zoom.size,但无法正确处理。 And don't know how to reset the zoomed section either. 而且也不知道如何重设缩放部分。

Any help would be much appreciated ! 任何帮助将非常感激 !

I´ll give an example of zooming some circles. 我将举一个放大一些圆圈的例子。 Clicking on the red rectangle will zoom out to 50%, clicking on the blue one will return to a 100% scale. 单击红色矩形将缩小到50%,单击蓝色矩形将返回100%比例。 The exact functions you are looking for are zoomOut() and initialZoom() 您要查找的确切函数是zoomOut()和initialZoom()

var zoomListener = d3.behavior.zoom().scaleExtent([0.1, 3]);

width = 200 ;
height = 200 ;

//svg
var svg = d3.select("body").append("svg").attr("id","vis")
.attr("width", width )
.attr("height", height );

//transition listener group
var svgGroup = svg.append("g").call(zoomListener);

//zoom in and zoom out buttons
svg.append("rect").attr("x",0).attr("y",0).attr("width",50).attr("height",50).style("fill","red").on("click",zoomOut);
svg.append("rect").attr("x",0).attr("y",50).attr("width",50).attr("height",50).style("fill","blue").on("click",initialZoom);


var i,k;
for(i=90;i<width-20;i+=20){
    for( k=20;k<height-20;k+=20){
        svgGroup.append("circle").attr("cx", i).attr("cy", k).attr("r", 10);
    }   
}


function zoomOut(){
    //fix transition to center of canvas
    x = (width/2) * 0.5;
    y = (height/2) * 0.5;
    //zoom transition- scale value 150%
    svgGroup.transition().duration(500).attr("transform", "translate("+x+","+y+")scale(0.5)" );
}

function initialZoom(){
    //fix transition to center of canvas
    x = (width/2) ;
    y = (height/2) ;
    //zoom transition- scale value 100%
    svgGroup.transition().duration(500).attr("transform", "scale(1)" );
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM