Random walk in two dimensions. Path is drawn with transparency to show more frequently traversed points darker than others.
Last active
August 29, 2015 14:10
-
-
Save munshkr/a270a39f571cea42167f to your computer and use it in GitHub Desktop.
Random walk
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
<!doctype html> | |
<meta charset="utf-8"> | |
<body> | |
<script src="http://d3js.org/d3.v3.min.js"></script> | |
<script> | |
var width = 960, | |
height = 500; | |
var step = 3, | |
stepsPerFrame = 10; | |
var initialPos = { x: width / 2, y: height / 2 }; | |
var pos = { x: initialPos.x, y: initialPos.y }; | |
var canvas = d3.select("body").append("canvas") | |
.attr("width", width) | |
.attr("height", height); | |
var ctx = canvas.node().getContext("2d"); | |
ctx.lineWidth = 1.5; | |
ctx.strokeStyle = 'rgba(0,0,0,.1)'; | |
var walkFrom = function(pos) { | |
if (Math.random() > 0.5) { | |
pos.x += step; | |
} else { | |
pos.x -= step; | |
} | |
if (Math.random() > 0.5) { | |
pos.y += step; | |
} else { | |
pos.y -= step; | |
} | |
} | |
var reset = function(ctx, pos) { | |
ctx.clearRect(0, 0, width, height); | |
pos.x = initialPos.x; | |
pos.y = initialPos.y; | |
} | |
var i = 0; | |
var iOut = 0; | |
var loop = function() { | |
for (var j = 0; j < stepsPerFrame; j++) { | |
ctx.beginPath(); | |
ctx.moveTo(pos.x, pos.y); | |
walkFrom(pos); | |
ctx.lineTo(pos.x, pos.y); | |
ctx.closePath(); | |
ctx.stroke(); | |
}; | |
// If it wanders outside of canvas for too long, reset walk | |
if (pos.x < 0 || pos.x > width || pos.y < 0 || pos.y > height) { | |
iOut += 1; | |
} else { | |
iOut = 0; | |
} | |
if (iOut > 100) { | |
reset(ctx, pos); | |
} | |
requestAnimationFrame(loop); | |
} | |
reset(ctx, pos); | |
requestAnimationFrame(loop); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment