Created
December 23, 2018 11:50
-
-
Save ikr7/32a2dfc2634dabedc85dd5c0bc3040c8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="en" dir="ltr"> | |
<head> | |
<meta charset="utf-8"> | |
<title>Population Pyramid Simulation</title> | |
<style media="screen"> | |
body { | |
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; | |
position: relative; | |
} | |
canvas { | |
background: #def; | |
} | |
div { | |
position: absolute; | |
top: 1em; | |
left: 1em; | |
} | |
</style> | |
</head> | |
<body> | |
<canvas></canvas> | |
<div id="pop"></div> | |
<script> | |
const $ = document.querySelector.bind(document); | |
const width = 1000; | |
const height = 505; | |
const canvas = $('canvas'); | |
const context = canvas.getContext('2d'); | |
const pop = $('#pop'); | |
document.body.style.width = width; | |
document.body.style.height = height; | |
canvas.width = width; | |
canvas.height = height; | |
const N = 101; | |
let pyramid = []; | |
for (let i = 0; i < N; i++) { | |
pyramid[i] = 500 - 5 * (i + 1); | |
} | |
let mr = [2.1, 0.3, 0.2, 0.2, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.3, 0.3, 0.3, 0.3, 0.3, 0.4, 0.4, 0.4, 0.4, 0.4, 0.5, 0.5, 0.5, 0.5, 0.5, 0.8, 0.8, 0.8, 0.8, 0.8, 1.2, 1.2, 1.2, 1.2, 1.2, 1.9, 1.9, 1.9, 1.9, 1.9, 2.7, 2.7, 2.7, 2.7, 2.7, 3.9, 3.9, 3.9, 3.9, 3.9, 5.8, 5.8, 5.8, 5.8, 5.8, 9.4, 9.4, 9.4, 9.4, 9.4, 17.4, 17.4, 17.4, 17.4, 17.4, 34.4, 34.4, 34.4, 34.4, 34.4, 68.5, 68.5, 68.5, 68.5, 68.5, 133.7, 133.7, 133.7, 133.7, 133.7, 238, 238, 238, 238, 238, 404.3]; | |
function draw (year) { | |
context.clearRect(0, 0, width, height); | |
let sum = 0; | |
for (let i = 0; i < N; i++) { | |
const p = pyramid[i]; | |
context.fillRect( | |
width / 2 - p / 2, | |
(N - i - 1) * (height / N), | |
p, | |
height / N, | |
); | |
sum += p; | |
} | |
pop.innerText = `YEAR ${year} \n POPULATION ${Math.round(sum)}`; | |
} | |
const tfr = 2.019; | |
function step () { | |
const new_pyramid = []; | |
for (let i = 0; i < N - 1; i++) { | |
new_pyramid[i + 1] = (1 - mr[i] / 1000) * pyramid[i]; | |
} | |
new_pyramid[N - 1] += (1 - mr[N - 1] / 1000) * pyramid[N - 1]; | |
let hm = 0; | |
for (let i = 15; i <= 49; i++) { | |
hm += 1.0 / (pyramid[i] / 2); | |
} | |
new_pyramid[0] = (49 - 15 + 1) * tfr / hm; | |
pyramid = new_pyramid; | |
} | |
canvas.addEventListener('click', () => { | |
draw(0); | |
step(); | |
}, false); | |
function animate (year) { | |
draw(year); | |
step(); | |
setTimeout(() => { | |
animate(year + 1) | |
}, 1000 / 50); | |
} | |
animate(0); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment