Demonstrates how to programmatically set the x-domain used by D3’s zoom behaviour, in answer to a StackOverflow question.
xxxxxxxxxx
<meta charset="utf-8">
<title>Zoom Behaviour and Timer</title>
<script src="https://d3js.org/d3.v2.min.js?2.10.1"></script>
<style>
body {
font-family: sans-serif;
}
.noselect {
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
svg {
font: 10px sans-serif;
shape-rendering: crispEdges;
}
rect {
fill: #ddd;
}
rect.zoom {
stroke: steelblue;
fill-opacity: 0.5;
}
.axis path, .axis line {
fill: none;
stroke: #fff;
}
</style>
<body>
<script>
var margin = {top: 0, right: 12, bottom: 12, left: 36},
width = 960 - margin.left - margin.right,
height = 430 - margin.top - margin.bottom;
var x0 = d3.scale.linear()
.domain([-width / 2, width / 2])
.range([0, width]),
x = x0.copy();
var y = d3.scale.linear()
.domain([-height / 2, height / 2])
.range([height, 0]);
var xAxis = d3.svg.axis()
.scale(x)
.orient("bottom")
.tickSize(-height);
var yAxis = d3.svg.axis()
.scale(y)
.orient("left")
.ticks(5)
.tickSize(-width);
var zoom = d3.behavior.zoom()
.scaleExtent([1, Infinity])
.x(x)
.y(y)
.on("zoom", refresh);
var timer = true;
var svg = d3.select("body").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")")
.call(zoom)
.on("mousedown", function() { timer = false; })
.on("mouseup", function() { timer = true; });
svg.append("rect")
.attr("width", width)
.attr("height", height);
svg.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis);
svg.append("g")
.attr("class", "y axis")
.call(yAxis);
setInterval(function() {
if (!timer) return;
var translate = zoom.translate(),
scale = zoom.scale(),
xd = x0.domain(),
dx = 1;
// Set a new x-domain: offset by dx.
xd[0] += dx;
xd[1] += dx;
x0.domain(xd)
// Set the zoom x-domain (this resets the domain at zoom scale=1).
zoom.x(x.domain(xd));
// Reset the domain relative to the current zoom offsets.
x.domain(x0.range().map(function(x) { return (x - translate[0]) / scale; }).map(x0.invert));
refresh();
}, 1e3);
function refresh() {
svg.select(".x.axis").call(xAxis);
svg.select(".y.axis").call(yAxis);
}
</script>
Modified http://d3js.org/d3.v2.min.js?2.10.1 to a secure url
https://d3js.org/d3.v2.min.js?2.10.1