Simple Line Chart Example
Using the HTML5 canvas to render lines and circles.
HTML
<div>Number of times an extinction occured within 1000 steps, out of 20,000 experiments:</div>
<table>
<tr><th>Random walk</th><th>Mirrored walk</th></tr>
<tr id="results"></tr>
</table>
<div>
Mirrored Walk went extinct <span id="percent"></span>% of the times Random Walk did.
</div>
CSS
div {
margin: 10px;
}
table, th, td {
margin: 10px;
padding: 4px;
border: 1px solid #888;
}
JavaScript
/* var canvas = document.getElementById('randomWalk');
var ctx = canvas.getContext('2d');
ctx.lineWidth = 1; */
var randExt = 0;
var cappedExt = 0;
for (var exp = 0; exp < 1000; exp++) {
var whiteRabbits = 30;
var brownRabbits = 30;
for (var i = 0; i < 5000; i++) {
var nextWhiteRabbits;
var nextBrownRabbits;
if (whiteRabbits > 0) {
if (Math.random() < 0.5) {
whiteRabbits++;
} else {
whiteRabbits--;
}
}
if (brownRabbits > 0) {
if (Math.random() < 0.5) {
brownRabbits++;
} else {
brownRabbits--;
}
}
/*
ctx.beginPath();
ctx.strokeStyle = 'red';
ctx.moveTo(i, 100-whiteRabbits);
ctx.lineTo(i+1, 100-nextWhiteRabbits);
ctx.stroke();
ctx.beginPath();
ctx.strokeStyle = 'black';
ctx.moveTo(i, 100-brownRabbits);
ctx.lineTo(i+1, 100-nextBrownRabbits);
ctx.stroke();
*/
/* whiteRabbits = nextWhiteRabbits;
brownRabbits = nextBrownRabbits; */
}
if (whiteRabbits === 0 || brownRabbits === 0) {
randExt++;
}
// ****
/* canvas = document.getElementById('capped');
ctx = canvas.getContext('2d');
ctx.lineWidth = 1; */
whiteRabbits = 30;
brownRabbits = 30;
for (var i = 0; i < 5000; i++) {
var nextWhiteRabbits;
var nextBrownRabbits;
if (Math.random() < 0.5) {
if (whiteRabbits > 0) whiteRabbits++;
if (brownRabbits > 0) brownRabbits--;
} else {
if (whiteRabbits > 0) whiteRabbits--;
if (brownRabbits > 0) brownRabbits++;
}
/* ctx.beginPath();
ctx.strokeStyle = 'red';
ctx.moveTo(i, 100-whiteRabbits);
ctx.lineTo(i+1, 100-nextWhiteRabbits);
ctx.stroke();
ctx.beginPath();
ctx.strokeStyle = 'black';
ctx.moveTo(i, 100-brownRabbits);
ctx.lineTo(i+1, 100-nextBrownRabbits);
ctx.stroke();
whiteRabbits = nextWhiteRabbits;
...