Skip to content

Instantly share code, notes, and snippets.

@d3byex
Created November 24, 2015 03:43
Show Gist options
  • Save d3byex/6cad2e28e0896b5108f6 to your computer and use it in GitHub Desktop.
Save d3byex/6cad2e28e0896b5108f6 to your computer and use it in GitHub Desktop.
D3byEX 8.5: Pan and Zoom
<!DOCTYPE html>
<html>
<head>
<meta name="description" content="D3byEX 8.5" />
<meta charset="utf-8">
</head>
<body>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script>
var zoomBehavior = d3.behavior.zoom()
.scaleExtent([0.1, 10])
.on("zoom", onZoom);
var width = 400, height = 300, radius = 50;
var svg = d3.select("body").append("svg")
.attr({ "width": width, "height": height })
.call(zoomBehavior);
var dragBehavior = d3.behavior.drag()
.on("drag", onDrag);
//.on("dragstart", function() {
// d3.event.sourceEvent.stopPropagation();
//});
// uncomment to prevent pan / drag conflict
var data = [
[width / 2 - radius, height / 2 - radius],
[width / 2 - radius, height / 2 + radius],
[width / 2 + radius, height / 2 - radius],
[width / 2 + radius, height / 2 + radius]
];
var colors = d3.scale.category10();
var circles = svg.selectAll("circle")
.data(data).enter().append("circle")
.each(function(d, i) {
d3.select(this).attr({
'r': radius,
'transform': 'translate(' + d + ')',
'fill': colors
});
});
circles.call(dragBehavior);
function onDrag(d) {
var x = d3.event.x, y = d3.event.y;
d3.select(this)
.attr("transform", function(d) {
return "translate(" + x + ", " + y + ")";
});
}
function onZoom() {
console.log(d3.event.translate);
console.log(d3.event.scale);
svg.attr("transform", "translate(" + d3.event.translate + ")" +
"scale(" + d3.event.scale + ")");
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment