Help would be appreciated updating the code below to work in version 4. I have changed zoom.behaviour to d3.zoom but I'm not clear about the other changes that are needed. It looks more complicated than v3!
<!DOCTYPE html>
<html>
<head>
<!-- <script type="text/javascript" src="http://d3js.org/d3.v3.js"></script>-->
<script data-require="[email protected]" data-semver="4.0.0" src="https://d3js.org/d3.v4.min.js"></script>
<style type="text/css">
body, html {
width: 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>
Change this:
.call(d3.zoom().on("zoom", function () {
svg.attr("transform", "translate(" + d3.event.translate
+ ")" + " scale(" + d3.event.scale + ")")
}))
To this:
.call(d3.zoom().on("zoom", function () {
svg.attr("transform", d3.event.transform)
}))
Here is the fiddle: https://jsfiddle.net/gerardofurtado/c8bga82b/
I can't reply to your comment to the answer, but here is how to zoom only the x-axis:
svg.attr(
"transform",
'translate('+d3.event.transform.x+',0) scale('+d3.event.transform.k+',1)'
)}))
Updated jsFiddle: https://jsfiddle.net/axge6a04/1/
The accepted answer is great !
For those of you who want to restrict the pan & zoom in boundaries (like here)..
Change this:
// 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 + ")");
});
To this:
.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);
}));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With