mapCanvas = (d3projection, map, centerX, centerY, scaleFactor=5, width=800, height=800, fillOne='#a2d2ff', fillTwo='#cdb4db') => {
const projection = d3projection
.center([centerX, centerY])
.translate([width/2, height/2])
.scale(width * scaleFactor)
const path = d3.geoPath()
.projection(projection)
// Data
// Map each raw feature to the path corresponding to it, e.g. path(franceCommunes.features[0]) produces a path string
// Add any additional properties for the map, such as colours
const mapData = map.features.map((d, i) => ({
d: path(d),
centroid: path.centroid(d),
fill: i%5 === 0 ? fillOne : fillTwo // random colours
}))
// Function to draw the map on canvas
const drawMap = (ctx) => {
ctx.fillStyle = '#ffffff'
for (const { d, fill } of mapData) {
const p = new Path2D(d)
ctx.fillStyle = fill
ctx.strokeStyle = '#fff'
ctx.lineWidth = 1
ctx.stroke(p)
ctx.fill(p)
}
}
// Function to draw the centroids of the map on canvas
const drawCentroids = (ctx) => {
for (const { centroid } of mapData) {
ctx.fillStyle = '#fff'
ctx.beginPath();
ctx.arc(centroid[0], centroid[1], 2, 0, 2 * Math.PI);
ctx.fill();
}
}
// Draw the map on canvas
const ctx = DOM.context2d(width, height)
// Set canvas dimensions
const scale = Math.max(2, window.devicePixelRatio)
ctx.canvas.style.width = `${width}px`
ctx.canvas.style.height = `${height}px`
ctx.canvas.width = width * scale
ctx.canvas.height = height * scale
ctx.scale(scale, scale)
drawMap(ctx)
//drawCentroids(ctx) // uncomment this to see the centroids
return ctx.canvas;
}