Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

GlennMatthys commented Jun 2, 2020

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.