Skip to content

Instantly share code, notes, and snippets.

@oshea00
Last active March 19, 2026 05:31
Show Gist options
  • Select an option

  • Save oshea00/5726bfad4d66ced5c62320512dffe998 to your computer and use it in GitHub Desktop.

Select an option

Save oshea00/5726bfad4d66ced5c62320512dffe998 to your computer and use it in GitHub Desktop.
Random Walk
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Canvas Dot Demo</title>
<style>
body {
margin: 0;
font-family: Arial, sans-serif;
background: #f5f5f5;
display: grid;
place-items: center;
min-height: 100vh;
}
.wrap {
background: white;
padding: 20px;
border-radius: 16px;
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
}
canvas {
border: 1px solid #ccc;
display: block;
background: #fff;
}
</style>
</head>
<body>
<div class="wrap">
<h3>Random Walk</h3>
<canvas id="dotCanvas" width="500" height="300"></canvas>
</div>
<script>
function drawDot(ctx, x, y, radius) {
ctx.beginPath();
ctx.arc(x, y, radius, 0, Math.PI * 2);
ctx.fill();
}
function drawLine(ctx, from, to) {
ctx.strokeStyle = "black";
ctx.lineWidth = 2;
ctx.beginPath;
ctx.moveTo(from.x, from.y);
ctx.lineTo(to.x, to.y);
ctx.stroke();
}
function randomVector(b) {
const theta = Math.random() * 2 * Math.PI; // random direction
const magnitude = Math.random() * b; // random size from 0 to b
return {
x: magnitude * Math.cos(theta),
y: magnitude * Math.sin(theta)
};
}
function randomNormal(variance = 1) {
let u1 = 0;
let u2 = 0;
while (u1 === 0) u1 = Math.random();
while (u2 === 0) u2 = Math.random();
const z = Math.sqrt(-2 * Math.log(u1)) * Math.cos(2 * Math.PI * u2);
return Math.sqrt(variance) * z;
}
const canvas = document.getElementById('dotCanvas');
const ctx = canvas.getContext('2d');
mx = 500;
my = 300;
n = 30;
start = { x:0, y:0 }
walk = [start];
for (i=0;i<n;i++) {
v = randomVector(randomNormal());
to = {x: start.x+v.x, y: start.y+v.y};
walk.push(to);
start = { ...to };
}
const minX = Math.min(...walk.map(p=>p.x));
const minY = Math.min(...walk.map(p=>p.y));
const maxX = Math.max(...walk.map(p=>p.x));
const maxY = Math.max(...walk.map(p=>p.y));
const rangeX = maxX - minX || 1;
const rangeY = maxY - minY || 1;
const scaleX = (mx * 0.9) / rangeX;
const scaleY = (my * 0.9) / rangeY;
scaledWalk = walk.map(p=>({
x: Math.floor((p.x - minX) * scaleX + mx * 0.05),
y: Math.floor((p.y - minY) * scaleY + my * 0.05)
}));
from = scaledWalk[0];
drawDot(ctx, from.x, from.y, 3);
for (i=1;i<scaledWalk.length;i++) {
to = scaledWalk[i];
drawDot(ctx, to.x, to.y, 3);
drawLine(ctx, from, to);
from = to;
}
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment