Skip to content

Instantly share code, notes, and snippets.

@mbostock
Last active March 6, 2019 05:25
Show Gist options
  • Save mbostock/bf2f5f02b62b5b3bb92ae1b59b53da36 to your computer and use it in GitHub Desktop.
Save mbostock/bf2f5f02b62b5b3bb92ae1b59b53da36 to your computer and use it in GitHub Desktop.
Contour Plot III
license: gpl-3.0
redirect: https://observablehq.com/@d3/animated-contours
<!DOCTYPE html>
<canvas width="960" height="500"></canvas>
<script src="https://d3js.org/d3-array.v1.min.js"></script>
<script src="https://d3js.org/d3-color.v1.min.js"></script>
<script src="https://d3js.org/d3-contour.v1.min.js"></script>
<script src="https://d3js.org/d3-geo.v1.min.js"></script>
<script src="https://d3js.org/d3-interpolate.v1.min.js"></script>
<script src="https://d3js.org/d3-scale.v1.min.js"></script>
<script src="https://d3js.org/d3-scale-chromatic.v1.min.js"></script>
<script src="https://d3js.org/d3-timer.v1.min.js"></script>
<script>
// Populate a grid of (n+2)×(m+2) values where -9.6 ≤ x ≤ 9.6 and -5 ≤ y ≤ 5.
var n = 240, m = 125, values = new Array((n + 2) * (m + 2));
for (var j = -0.5, k = 0; j < m + 1; ++j) {
for (var i = -0.5; i < n + 1; ++i, ++k) {
values[k] = value(i / n * 19.2 - 9.6, 5 - j / m * 10);
}
}
var canvas = document.querySelector("canvas"),
context = canvas.getContext("2d"),
color = d3.scaleSequential(d3.interpolateRdBu).domain([-1, 1]),
path = d3.geoPath(null, context),
thresholds = d3.range(-1.2, 1, 0.2),
contours = d3.contours().size([n + 2, m + 2]);
context.scale(canvas.width / (n + 1), canvas.width / (n + 1));
context.translate(-0.5, -0.5);
d3.timer(function(t) {
var dv = (t % 1000) / 1000 * 0.2;
contours
.thresholds(thresholds.map(function(v) { return v + dv; }))
(values)
.forEach(fill);
});
function fill(geometry) {
context.beginPath();
path(geometry);
context.fillStyle = color(geometry.value);
context.fill();
}
function value(x, y) {
return Math.sin(x + y) * Math.sin(x - y);
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment