我有一个简单的svg矩形,我使用d3.js添加了缩放和平移。我还添加了一个按钮,以便在单击按钮后尝试重置缩放。这是代码:
<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)),但它似乎不起作用。有人可以告诉重置功能有什么问题吗?
答案 0 :(得分:3)
您需要以这种方式重写代码:
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);
});
&#13;
<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>
&#13;