Skip to content

Instantly share code, notes, and snippets.

@tomeustace
Created January 5, 2017 16:28
Show Gist options
  • Save tomeustace/64b59a7b6c269ceaaffdba0b987375c8 to your computer and use it in GitHub Desktop.
Save tomeustace/64b59a7b6c269ceaaffdba0b987375c8 to your computer and use it in GitHub Desktop.
d3 v4 translateBy, scaleBy and scaleTo example usage
<!DOCTYPE html>
<meta charset="utf-8">
<style>
.view {
fill: blue;
stroke: #000;
}
</style>
<h3>d3 v4 Zoom Experimentation</h3>
<p>Call zoom.translateBy, zoom.scaleBy and zoom.scaleTo on rect element. Then reset using d3.zoomIdentity.</p>
<svg width="500" height="500"> </svg>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script>
var svg = d3.select("svg"),
width = +svg.attr("width"),
height = +svg.attr("height");
var zoom = d3.zoom()
.on("start", zoomStarted)
.on("end", zoomEnded)
.on("zoom", zoomed);
var view = svg.append("rect")
.attr("class", "view")
.attr("x", 0.5)
.attr("y", 0.5)
.attr("width", width )
.attr("height", height );
setTimeout(function() {
view.transition().duration(1000).call(zoom.translateBy, 200, 100);
//Note: calling below would do same as above without transtiion
//zoom.translateBy(view, 200, 100);
}, 2000);
setTimeout(function() {
view.transition().duration(1000).call(zoom.scaleBy, 2);
//Note: calling below would do same as above without transtiion
//zoom.scaleBy(view, 2);
}, 4000);
setTimeout(function() {
view.transition().duration(1000).call(zoom.scaleTo, .5);
//Note: calling below would do same as above without transtiion
//zoom.scaleTo(view, .5);
}, 6000);
setTimeout(function() {
view.transition().duration(1000).call(zoom.transform, d3.zoomIdentity);
}, 8000);
function zoomStarted() {
console.log('zoomStarted() - transform ' + d3.event.transform.toString());
}
function zoomEnded() {
console.log('zoomEnded() - transform ' + d3.event.transform.toString());
}
function zoomed() {
console.log('zoomed() - applying transform ' + d3.event.transform.toString());
//below is actually applying the transform, comment it out and observe!!
view.attr("transform", d3.event.transform);
}
</script>
@adharshchottu
Copy link

thanks a lot

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment