D3具有力定向布局here.有什么方法可以将zoom 添加到此图表中吗?目前,我能够捕获鼠标滚轮事件,但不确定如何编写重绘函数本身.有什么建议吗?
var vis = d3.select("#graph")
.append("svg:svg")
.call(d3.behavior.zoom().on("zoom", redraw)) // <-- redraw function
.attr("width", w)
.attr("height", h);
D3具有力定向布局here.有什么方法可以将zoom 添加到此图表中吗?目前,我能够捕获鼠标滚轮事件,但不确定如何编写重绘函数本身.有什么建议吗?
var vis = d3.select("#graph")
.append("svg:svg")
.call(d3.behavior.zoom().on("zoom", redraw)) // <-- redraw function
.attr("width", w)
.attr("height", h);
Update 6/4/14
See also Mike Bostock's answer here for changes in D3 v.3 and the related example. I think this probably supersedes the answer below.
Update 2/18/2014
如果希望整个SVG能够平移和zoom ,我认为@ahaarnos的答案更可取.下面我的答案中嵌套的g
个元素只有在同一个SVG中有非zoom 元素时才是真正必要的(不是原始问题中的情况).如果将该行为应用于g
元素,则需要后台rect
或类似元素来确保g
接收指针事件.
Original Answer
我在zoom-pan-transform个例子的基础上实现了这一点——你可以在这里看到我的JSFIDLE:http://jsfiddle.net/nrabinowitz/QMKm3/
It was a bit more complex than I had hoped - you have to nest several g
elements to get it to work, set the SVG's pointer-events
attribute to all
, and then append a background rectangle to receive the pointer events (otherwise it only works when the pointer is over a node or link). The redraw
function is comparatively simple, just setting a transform on the innermost g
:
var vis = d3.select("#chart")
.append("svg:svg")
.attr("width", w)
.attr("height", h)
.attr("pointer-events", "all")
.append('svg:g')
.call(d3.behavior.zoom().on("zoom", redraw))
.append('svg:g');
vis.append('svg:rect')
.attr('width', w)
.attr('height', h)
.attr('fill', 'white');
function redraw() {
console.log("here", d3.event.translate, d3.event.scale);
vis.attr("transform",
"translate(" + d3.event.translate + ")"
+ " scale(" + d3.event.scale + ")");
}
This effectively scales the entire SVG, so it scales stroke width as well, like zooming in on an image.
There is another example that illustrates a similar technique.