本文介绍了如何在 d3.js 中重置缩放?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个简单的 svg 矩形,我使用 d3.js 在它上面添加了缩放和平移.我还添加了一个按钮,以便在单击按钮后尝试重置缩放.代码如下:
I have a simple svg rectangle and I have added zooming and panning on it using d3.js. I have also added a button in order to try and reset the zoom once the button is clicked. Here is the code:
<button>Reset</button>
<body>
<script>
function zoomed() {
svg.attr("transform", d3.event.transform)
}
var svg = d3.select("body")
.append("svg")
.attr("width", "100%")
.attr("height", "100%")
.call(d3.zoom().on("zoom", zoomed))
.append("g")
svg.append("rect")
.attr("x", 450)
.attr("y", 200)
.attr("width", 300)
.attr("height", 200)
.style("fill", "#B8DEE6")
$("#Reset").click(() => {
zoom.transform(container, d3.zoomIdentity.scale(1));
})
</script>
</body>
我尝试了 zoom.transform(container, d3.zoomIdentity.scale(1)) 但它似乎不起作用.谁能告诉我重置功能有什么问题?
I have tried zoom.transform(container, d3.zoomIdentity.scale(1)) but it does not seem to work. Can anybody please tell what is the problem with the resetting function?
推荐答案
你需要这样重写你的代码:
You need to rewrite your code this way:
function zoomed() {
gElem.attr("transform", d3.event.transform)
}
var zoom = d3.zoom().on("zoom", zoomed);
var svg = d3.select("body")
.append("svg")
.attr("width", "600")
.attr("height", "600")
var gElem = svg.append("g").call(zoom);
gElem.append("rect")
.attr("x", 50)
.attr("y", 50)
.attr("width", 300)
.attr("height", 200)
.style("fill", "#B8DEE6")
$("#Reset").click(() => {
gElem.transition()
.duration(750)
.call(zoom.transform, d3.zoomIdentity);
});
查看演示:
function zoomed() {
gElem.attr("transform", d3.event.transform)
}
var zoom = d3.zoom().on("zoom", zoomed);
var svg = d3.select("body")
.append("svg")
.attr("width", "400")
.attr("height", "200")
var gElem = svg.append("g").call(zoom);
gElem.append("rect")
.attr("x", 50)
.attr("y", 50)
.attr("width", 300)
.attr("height", 200)
.style("fill", "#B8DEE6")
$("#Reset").click(() => {
gElem.transition()
.duration(750)
.call(zoom.transform, d3.zoomIdentity);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.13.0/d3.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="Reset">RESET</button>
这篇关于如何在 d3.js 中重置缩放?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!