2016-05-16 18 views
2

我想利用D3的缩放行为功能,但我需要使用viewBox属性而不是transform方法对SVG进行所有转换/缩放,如D3例子:http://bl.ocks.org/mbostock/3680999如何在ViewBox中使用D3缩放行为而不是转换

我怎样才能达到这个规模/只使用viewBox翻译?这是我的代码到目前为止,这不像变换方法。

function zoomed(d) { 
    if (!scope.drawLine) { 
    var scale = d3.event.scale; 
    var translation = d3.event.translate; 

    //This works, but I can't use it for reason's I won't go into now 
    //mapSVG_G.attr("transform", "translate(" + d3.event.translate + ")scale(" + d3.event.scale + ")"); 

    var newViewBox = [ 
     initialViewBox[0] - translation[0], 
     initialViewBox[1] - translation[1], 
     initialViewBox[2]/scale, 
     initialViewBox[3]/scale 
     ]; 
     mapSVG.attr('viewBox', newViewBox); 
    } 
} 

回答

0

有点过,但可以为您服务的开始:

主片:

var newViewBox = [ 
    -translate[0]/scale, 
    -translate[1]/scale, 
    width/scale, 
    height/scale 
].join(" "); 

整个例如:

var width = 960, 
 
    height = 500; 
 

 
var randomX = d3.random.normal(width/2, 80), 
 
    randomY = d3.random.normal(height/2, 80); 
 

 
var data = d3.range(2000).map(function() { 
 
    return [ 
 
    randomX(), 
 
    randomY() 
 
    ]; 
 
}); 
 

 
var svg = d3.select("body").append("svg") 
 
    .attr("width", width) 
 
    .attr("height", height) 
 
    .attr("viewBox", [0, 0, width, height].join(" ")) 
 

 
var vis = svg.append("g") 
 
    .call(d3.behavior.zoom().scaleExtent([1, 8]).on("zoom", zoom)) 
 
    .append("g"); 
 

 
vis.append("rect") 
 
    .attr("class", "overlay") 
 
    .attr("width", width) 
 
    .attr("height", height); 
 

 
vis.selectAll("circle") 
 
    .data(data) 
 
    .enter().append("circle") 
 
    .attr("r", 2.5) 
 
    .attr("transform", function(d) { 
 
    return "translate(" + d + ")"; 
 
    }); 
 

 
function zoom() { 
 
    var scale = d3.event.scale; 
 
    var translate = d3.event.translate; 
 

 
    var newViewBox = [ 
 
    -translate[0]/scale, 
 
    -translate[1]/scale, 
 
    width/scale, 
 
    height/scale 
 
    ].join(" "); 
 
    
 
    svg.attr('viewBox', newViewBox); 
 

 
}
.overlay { 
 
    fill: none; 
 
    pointer-events: all; 
 
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>

+0

不幸的是,此解决方案的翻译功能不正确。 – Doughy