Created
January 5, 2017 16:25
-
-
Save tomeustace/f162eae7d2af9aa3d43bde3ccc990255 to your computer and use it in GitHub Desktop.
d3 v4 zoom transform
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<meta charset="utf-8"> | |
<style> | |
.view { | |
fill: blue; | |
stroke: #000; | |
} | |
</style> | |
<h3>d3 v4 Zoom Experimentation</h3> | |
<p>After timeout of 2 seconds apply transform, that shrinks view. After timeout of 4 seconds use d3.zoomIdentity to reset view to original transform.</p> | |
<p>Note: zoom is enabled on the view element as we call zoom on view. Hit f12 to see the start, zoom, end events fired.</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); | |
//call zoom, enables zooming of view element. Transform will be applied after timeout | |
view.call(zoom); | |
//after 2 seconds apply new transform on element | |
setTimeout(function() { | |
var transform = d3.zoomIdentity.translate(100, 50).scale(1); | |
view.transition().duration(1000).call(zoom.transform, transform); | |
}, 2000); | |
//after 4 seconds apply d3.zoomIdentity which sets the transform to be as defined on element | |
setTimeout(function() { | |
view.transition().duration(1000).call(zoom.transform, d3.zoomIdentity); | |
}, 4000); | |
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> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment