Skip to content

Instantly share code, notes, and snippets.

@hacknightly
Created April 5, 2019 04:24
Show Gist options
  • Save hacknightly/fd609abe5a7e15e223a823ee6e0724c8 to your computer and use it in GitHub Desktop.
Save hacknightly/fd609abe5a7e15e223a823ee6e0724c8 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>
@GlennMatthys
Copy link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment