感谢您提供帮助以更新下面的代码以在版本4中工作。我已将zoom.behaviour更改为d3.zoom,但我不清楚所需的其他更改。看起来比v3还要复杂!
<!DOCTYPE html> <html> <head> <!-- <script type="text/javascript" src="http://d3js.org/d3.v3.js"></script>--> <script data-require="d3@4.0.0" data-semver="4.0.0" src="https://d3js.org/d3.v4.min.js"></script> <style type="text/css"> body, html { 100%; height: 100%; margin: 0; } svg { position: absolute; top: 0; left: 0; } p { text-align: center; } </style> </head> <body> <p>Use the mouse to pan (click and move) / zoom (scrollwheel)</p> </body> <script type="text/javascript"> var svg = d3.select("body") .append("svg") .attr("width", "100%") .attr("height", "100%") .call(d3.zoom().on("zoom", function () { svg.attr("transform", "translate(" + d3.event.translate + ")" + " scale(" + d3.event.scale + ")") })) .append("g") svg.append("circle") .attr("cx", document.body.clientWidth / 2) .attr("cy", document.body.clientHeight / 2) .attr("r", 50) .style("fill", "#B8DEE6") </script> </html>
仅缩放x轴的方法:
svg.attr( "transform", 'translate('+d3.event.transform.x+',0) scale('+d3.event.transform.k+',1)' )}))
对于那些想要限制平移和缩放边界的人。
更改此:
// width, height = viewport width, height .call(d3.zoom().on("zoom", function () { var tx = Math.min(0, Math.max(d3.event.translate[0], width - width * d3.event.scale)); var ty = Math.min(0, Math.max(d3.event.translate[1], height - height * d3.event.scale)); svg.attr("transform", "translate(" + [tx, ty] + ") scale(" + d3.event.scale + ")"); });
对此:
.call(d3.zoom().on("zoom", function () { d3.event.transform.x = Math.min(0, Math.max(d3.event.transform.x, width - width * d3.event.transform.k)); d3.event.transform.y = Math.min(0, Math.max(d3.event.transform.y, height - height * d3.event.transform.k)); svg.attr("transform", d3.event.transform); }));