-
-
Save alexdiliberto/aaba234733396a7635f0557086b26596 to your computer and use it in GitHub Desktop.
A Random Walk in JavaScript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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