我正在尝试实现d3的平移和缩放功能。默认的平移和缩放效果很好,但要求我们还需要放大和缩小按钮。我还实现了缩放按钮,它也工作得很好。奇怪的是,当我第一次移动图像并点击缩放按钮时,图像会被移回之前的位置,不仅是当我第一次用鼠标缩放并再次用按钮开始缩放时,图像会缩放到默认值并再次开始缩放。如何从鼠标事件转移到按钮单击事件的位置开始缩放。
let imgHeight = 400,
imgWidth = 900,
width = 900,
height = 450;
let zoom = d3.zoom().scaleExtent([1, 8]).on("zoom", zoomed);
let svg = d3.select("#canvas").append("svg")
.attr("width", width + "px")
.attr("height", height + "px");
svg = svg.append("g")
.attr("transform", "translate(0,25)")
.call(zoom)
.append("g");
svg.append("image")
.attr("width", imgWidth + "px")
.attr("height", imgHeight + "px")
.attr("href", "https://www.w3schools.com/howto/img_fjords.jpg");
function zoomed() {
svg.attr("transform", d3.event.transform);
}
let zoomIn = d3.select("#zoom-in");
zoomIn.on("click", function() {
zoom.scaleBy(svg.transition().duration(750), 1.2);
})<div id='canvas'>
</div>
<div id="tools">
<button id="zoom-in">
+
</button>
</div>
<script src="https://d3js.org/d3.v4.min.js"></script>
发布于 2018-01-19 01:19:45
你在两个不同的"g“元素上调用zoom,你只需要追加一次,只需删除第二个追加。
svg = svg.append("g")
.attr("transform", "translate(0,25)")
.call(zoom)这就是您遇到这个问题的原因,缩放函数被应用于嵌套元素
https://stackoverflow.com/questions/48326571
复制相似问题