Reputation: 3
I am trying to create a d3-contour map using solar radiation as a google maps overlay using canvas not svg. I am new to d3 and am developing my js knowledge, I'm struggling to find complete examples on the interwebs to work from.
As an initial step I have made some dummy data for a 7 x 7 grid with made up values (10-40) which I want to display on a html page without google maps.
I use d3-contour which creates MultiPolygons. I am trying to draw these to a canvas element. With my code, nothing appears in html however no errors are in the console. Here is my code...
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="https://d3js.org/d3-hsv.v0.1.min.js"></script>
<script src="https://d3js.org/d3-contour.v1.min.js"></script>
<title>Untitled Document</title>
</head>
<body>
<canvas id="canvas" width="1000" height="1000"></canvas>
<script>
values = [10,10,10,10,10,10,10,20,20,20,20,20,20,20,30,30,30,30,30,30,30, 40,40,40,40,40,40,40,30,30,30,30,30,30,30,20,20,20,20,20,20,20,10,10,10,10,10,10,10];
var n = 7,
m = 7,
canvas = document.querySelector("canvas"),
context = canvas.getContext("2d"),
path = d3.geoPath().context(context);
contours = d3.contours().size([n, m]);
projection = d3.geoIdentity().scale(canvas.width / n),
path = d3.geoPath(projection, context);
function update(data) {
context.beginPath();
path(contours
.thresholds(d3.range(0, 50, 10))(data));
context.stroke();
}
update(values);
</script>
</body>
</html>
Upvotes: 0
Views: 1346
Reputation: 28783
You must draw each individual MultiPolygon
.
I have defined a little more interesting DEM samples.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="https://d3js.org/d3-hsv.v0.1.min.js"></script>
<script src="https://d3js.org/d3-contour.v1.min.js"></script>
<title>d3-contour-multipolygon</title>
</head>
<body>
<canvas id="canvas" width="200" height="200"></canvas>
<script>
values = [10,10,10,10,10,10,10,
20,20,20,20,20,20,20,
30,30,30,30,30,30,30,
40,40,40,40,40,40,40,
30,30,30,30,30,30,30,
20,20,20,20,20,20,20,
10,10,10,10,10,10,10];
values = [ 0, 0, 0, 0, 0, 0, 0,
0,20,25,29,21,22, 0,
0, 0,39,32,33,10, 0,
0,10,40,50,42,40, 0,
0, 0,31,39,34,24, 0,
0,12,22,31,26,23, 0,
0, 0, 0, 0, 0, 0, 0];
var n = 7,
m = 7,
canvas = document.querySelector("canvas"),
context = canvas.getContext("2d"),
// path = d3.geoPath().context(context);
contours = d3.contours().size([n, m]);
projection = d3.geoIdentity().scale(canvas.width / n),
path = d3.geoPath(projection, context);
function update(data) {
var cntrs = contours.thresholds(d3.range(0, 60, 10))(data);
cntrs.forEach(c => {
if (c.coordinates.length == 0) return;
context.beginPath();
// path(contours.thresholds(d3.range(0, 60, 10))(data));
path(c);
context.stroke();
});
}
update(values);
</script>
</body>
</html>
Upvotes: 1