Created
April 5, 2019 04:24
-
-
Save hacknightly/fd609abe5a7e15e223a823ee6e0724c8 to your computer and use it in GitHub Desktop.
A Random Walk in JavaScript
This file contains 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
https://jsfiddle.net/zhew5ns9/