Skip to content

Instantly share code, notes, and snippets.

@alexdiliberto
Forked from hacknightly/random-walk.html
Created January 25, 2021 02:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexdiliberto/aaba234733396a7635f0557086b26596 to your computer and use it in GitHub Desktop.
Save alexdiliberto/aaba234733396a7635f0557086b26596 to your computer and use it in GitHub Desktop.
A Random Walk in JavaScript
<html>
<head>
<style>
body {
padding: 0;
margin: 0;
height: 100%;
width: 100%;
display: flex;
justify-content: center;
align-items: center;
}
#canvas {
border: 1px solid whiteSmoke;
}
</style>
</head>
<body>
<canvas id="canvas" height="500" width="750"></canvas>
</body>
<script>
let x = random(0, 750);
let y = random(0, 500);
function random(min, max) {
return Math.random() * (max - min) + min;
}
function init() {
window.requestAnimationFrame(draw);
}
function draw() {
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
const nextX = random(-5, 5);
const nextY = random(-5, 5);
ctx.beginPath();
ctx.moveTo(x, y);
x += random(-5, 5);
y += random(-5, 5);
ctx.lineWidth = 5;
ctx.lineTo(x, y);
ctx.stroke();
window.requestAnimationFrame(draw);
}
init();
</script>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment