Created
June 18, 2013 10:34
-
-
Save alexlangberg/5804301 to your computer and use it in GitHub Desktop.
Create a simple pan/zoom interface with D3
This file contains hidden or 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> | |
<html lang="en"> | |
<head> | |
<meta charset="utf-8"> | |
<title>D3 pan and zoom sample</title> | |
<script src="http://code.jquery.com/jquery-2.0.2.min.js" type="text/javascript"></script> | |
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script> | |
<style type="text/css"> | |
html, body { | |
margin: 0; | |
padding: 0; | |
height: 100%; | |
min-height: 100%; | |
} | |
svg { | |
display: block; | |
} | |
#visualization { | |
width: 100%; | |
height: 100%; | |
background: grey; | |
} | |
</style> | |
</head> | |
<body id="home"> | |
<div id="visualization"></div> | |
<script type="text/javascript"> | |
// use jQuery to get width and height of containing element | |
var element = "#visualization"; | |
var width = $(element).width(); | |
var height = $(element).height(); | |
// add svg element | |
var svg = d3.select(element) | |
.append("svg"); | |
// add rect to fill entire svg and make it zoomable (the svg is not zoomable so we need this) | |
var rectangle = svg.append("svg:rect") | |
.attr("width", "100%") | |
.attr("height", "100%") | |
.attr("fill", "teal") | |
.call(d3.behavior.zoom().on("zoom", zoomed)); | |
// add a group with id "vis" that we will draw on | |
var vis = svg.append("svg:g") | |
.attr("id", "vis"); | |
// draw a rectangle that we can pan and zoom around with. | |
vis.append("svg:rect") | |
.attr("fill", "blue") | |
.attr("width", 100) | |
.attr("height", 100) | |
.attr("x", width/2) | |
.attr("y", height/2); | |
// when the user executes a zoom function, like dragging with the mouse or using the scrollwheel, we move the group with id "vis" | |
function zoomed() { | |
console.log("zoom"); | |
vis.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