Public
Edited
Dec 17, 2024
Comparing Canvas and SVG
A world map using Canvas and GeoJSON
Insert cell
Insert cell
Insert cell
<canvas id="map" width="900" height="450"></canvas>
Insert cell
ctx = canvas.getContext("2d");
Insert cell
Insert cell
world = await FileAttachment("world-lowres.geojson").json()
Insert cell
Insert cell
function initOcean() {
ctx.fillStyle = 'lightblue';
ctx.fillRect(0, 0, canvas.width, canvas.height);
}
Insert cell
function initLand() {
ctx.strokeStyle = 'white';
ctx.fillStyle = 'rgb(50,100,80)';
}
Insert cell
Insert cell
drawMap(world.features)
Insert cell
function drawMap(data) {
initOcean();
initLand();
data.forEach(obj => {
if(obj.geometry.type === 'MultiPolygon') {
obj.geometry.coordinates.forEach(poly => drawPolygon(poly[0]));
} else if(obj.geometry.type === 'Polygon') {
obj.geometry.coordinates.forEach(poly => drawPolygon(poly));
}
});
}
Insert cell
Insert cell
function drawPolygon(coords) {
ctx.beginPath();
for(let i = 0; i < coords.length; i++ ) {
let latitude = coords[i][1];
let longitude = coords[i][0];
if(i === 0) {
ctx.moveTo(scaleX(longitude), scaleY(latitude));
} else {
ctx.lineTo(scaleX(longitude), scaleY(latitude));
}
}
ctx.stroke();
ctx.fill();
}
Insert cell
scaleX = coord => canvas.width * (180 + coord) / 360;
Insert cell
scaleY = coord => canvas.height * (90 - coord) / 180;
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more