Skip to content

Instantly share code, notes, and snippets.

@i-like-robots
Last active Mar 30, 2022
Embed
What would you like to do?
Visualise ESRI ASCII grid
const fs = require('fs/promises')
const { createCanvas } = require('canvas')
function colorScale(p) {
if (p === 0) return 'white'
if (p < 50) return '#bad2eb'
if (p < 250) return '#8ebeda'
if (p < 500) return '#5a9ecc'
if (p < 1000) return '#357eb9'
if (p < 5000) return '#1c5ba6'
return '#0b3281'
}
async function loadData(file) {
const content = await fs.readFile(file, 'utf8')
const data = []
content.split(/\n+/).forEach((line) => {
if (/^[0-9-]/.test(line)) {
const items = line.trim().split(/\s+/)
data.push(items)
}
})
return data
}
async function draw() {
// it's only 4.5MB so no need to stream, just bodge!
const data = await loadData('./UK_residential_population_2011_1_km.asc')
const canvas = createCanvas(652, 1211)
const ctx = canvas.getContext('2d')
data.forEach((row, y) => {
row.forEach((value, x) => {
const pop = value === '-9999' ? 0 : parseInt(value, 10)
ctx.fillStyle = colorScale(pop)
ctx.fillRect(x, y, 1, 1)
})
})
await fs.writeFile('./map.png', canvas.toBuffer('image/png'))
}
draw()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment