Skip to content

Instantly share code, notes, and snippets.

@evanjmg
Last active February 19, 2017 16:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save evanjmg/7c43c37b1f7752a1ff438109f655bed3 to your computer and use it in GitHub Desktop.
Save evanjmg/7c43c37b1f7752a1ff438109f655bed3 to your computer and use it in GitHub Desktop.
Simple Zoom Example d3 v4
license: gpl-3.0
<!DOCTYPE html>
<meta charset="utf-8">
<style>
.axis path {
display: none;
}
.axis line {
stroke-opacity: 0.3;
shape-rendering: crispEdges;
}
svg,
#chart-container {
width: 100%;
height: 100vh;
display: block;
}
</style>
<body>
<div id="chart-container"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.5.0/d3.js"></script>
<script>
// select chart div and get the width and height of it.
var containerStyle = document.querySelector('#chart-container').getBoundingClientRect();
var svg = null,
width = containerStyle.width,
height = containerStyle.height,
gX = null,
gY = null,
currentTransform = null,
svg = d3.select("#chart-container").append('svg'),
view = svg.append("g")
.attr("class", "view");
if (currentTransform) view.attr('transform', currentTransform);
var xScale = d3.scaleLinear()
.domain([-width / 2, width / 2])
.range([0, width]);
var yScale = d3.scaleLinear()
.domain([-height / 2, height / 2])
.range([height, 0]);
var xAxis = d3.axisBottom(xScale)
.ticks((width + 2) / (height + 2) * 10)
.tickSize(height)
.tickPadding(8 - height);
var yAxis = d3.axisRight(yScale)
.ticks(10)
.tickSize(width)
.tickPadding(8 - width);
gX = svg.append("g")
.attr("class", "axis axis--x")
.call(xAxis);
gY = svg.append("g")
.attr("class", "axis axis--y")
.call(yAxis);
var zoom = d3.zoom()
.scaleExtent([0.5, 5])
.translateExtent([
[-width * 2, -height * 2],
[width * 2, height * 2]
])
.on("zoom", zoomed);
function zoomed() {
currentTransform = d3.event.transform;
view.attr("transform", currentTransform);
gX.call(xAxis.scale(d3.event.transform.rescaleX(xScale)));
gY.call(yAxis.scale(d3.event.transform.rescaleY(yScale)));
}
svg.call(zoom);
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment