程序缩放后使用鼠标时d3.js平移和缩放会跳转 [英] d3.js pan and zoom jumps when using mouse after programatic zoom
问题描述
我正在尝试在d3图形加载时居中.所以我跑
I'm trying to center my d3 graph when it loads. So I run
var g = svg.append("g");
//... then later
g.call(zoom.transform, center);
实际上并没有居中,只是在扩展.但是规模是可行的.问题是,当我然后滚动以放大或缩小时,它是从1
而不是0.5
开始的.所以它跳了.
It's not actually centering, it's just scaling right now. But the scale works. The problem is, when I then scroll to zoom in or out, it starts from 1
instead of 0.5
. So it jumps.
这是我的 jsbin .
推荐答案
您正在将事件应用到另一个对象(g
),然后将其设置在缩放对象上(svg
).由于缩放事件是针对应用于该元素的元素引用的,因此d3
现在不再与您的初始居中有关.从文档:
You are applying your event on a different object (the g
) then what the zoom is set up on (the svg
). Since the zoom event is referenced against the element it is applied to, d3
does not now about your initial centering. From the docs:
缩放行为将缩放状态存储在元素的 缩放行为已应用,而不是缩放行为本身.这是 因为缩放行为可以应用于许多元素 同时,每个元素都可以独立缩放.变焦 状态可以根据用户互动或通过编程方式更改 zoom.transform.
The zoom behavior stores the zoom state on the element to which the zoom behavior was applied, not on the zoom behavior itself. This is because the zoom behavior can be applied to many elements simultaneously, and each element can be zoomed independently. The zoom state can change either on user interaction or programmatically via zoom.transform.
将呼叫更改为svg.call(zoom.transform, center);
可解决您的问题.
Changing your call to svg.call(zoom.transform, center);
fixes your issue.
完整代码:
var svg = d3.select("svg"),
width = +svg.attr("width"),
height = +svg.attr("height"),
transform = d3.zoomIdentity;
var points = d3.range(2000).map(phyllotaxis(10));
var zoom = d3.zoom()
.scaleExtent([1 / 2, 8])
.on("zoom", zoomed);
var g = svg.append("g");
g.selectAll("circle")
.data(points)
.enter().append("circle")
.attr("cx", function(d) { return d.x; })
.attr("cy", function(d) { return d.y; })
.attr("r", 2.5)
.call(d3.drag()
.on("drag", dragged));
svg.call(zoom);
function zoomed() {
g.attr("transform", d3.event.transform);
}
function center() {
return d3.zoomIdentity
.scale(0.5);
}
function dragged(d) {
d3.select(this).attr("cx", d.x = d3.event.x).attr("cy", d.y = d3.event.y);
}
function phyllotaxis(radius) {
var theta = Math.PI * (3 - Math.sqrt(5));
return function(i) {
var r = radius * Math.sqrt(i), a = theta * i;
return {
x: width / 2 + r * Math.cos(a),
y: height / 2 + r * Math.sin(a)
};
};
}
svg.call(zoom.transform, center);
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<svg width="960" height="500"></svg>
<script src="https://d3js.org/d3.v4.min.js"></script>
</body>
</html>
这篇关于程序缩放后使用鼠标时d3.js平移和缩放会跳转的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!