Random Walker with D3.js.
Allow path to walk until it reaches the bounds of the svg. Use random number to determine direction, then update path data. Inspired by Coding Train Coding Challenge
Random Walker with D3.js.
Allow path to walk until it reaches the bounds of the svg. Use random number to determine direction, then update path data. Inspired by Coding Train Coding Challenge
<html> | |
<head></head> | |
<body> | |
<script src="https://d3js.org/d3.v4.min.js"></script> | |
<script> | |
var width = 1000, | |
height = 1000, | |
startX = width / 2, | |
startY = height / 2, | |
i = 0, // use i to track current point | |
walking, | |
svg = d3.select('body') | |
.append('svg') | |
.attr('width', width) | |
.attr('height', height) | |
.style('background-color', 'steelblue'), | |
renderPath = d3.line() | |
.x(function(d) { | |
return d.x; | |
}) | |
.y(function(d) { | |
return d.y; | |
}), | |
path = svg.append('path') | |
.datum([{ | |
x: startX, | |
y: startY | |
}]) | |
.attr('stroke-width', 2) | |
.attr('stroke', '#fff') | |
.attr('fill', 'none'); | |
init(); | |
//set first movement, initiate walker | |
function init() { | |
path.datum().push({ | |
x: (startX + 1), | |
y: startY | |
}); | |
path.attr('d', renderPath); | |
walking = setInterval(function() { | |
pathwalker(); | |
}, 10); | |
} | |
function pathwalker() { | |
i++; //increment i | |
var r = getRandomNumber(1, 4), | |
d = path.datum()[i], //always use most recent datum to find current point | |
p = { | |
x: 0, | |
y: 0 | |
}; | |
if (r === 1) { | |
//go up | |
p.x = d.x; | |
p.y = d.y - 10; | |
} else if (r === 2) { | |
//go right | |
p.x = d.x + 10; | |
p.y = d.y; | |
} else if (r === 3) { | |
//go down | |
p.x = d.x; | |
p.y = d.y + 10; | |
} else if (r === 4) { | |
//go left | |
p.x = d.x - 10; | |
p.y = d.y; | |
} | |
//if goes out of bounds stop walker | |
if (p.x > width || p.x < 0 || p.y > height || p.y < 0) { | |
console.log('OUT OF BOUNDS!'); | |
clearInterval(walking); | |
} | |
path.datum().push(p); | |
path.attr('d', renderPath); | |
}; | |
//util: get random number between 2 inputs | |
function getRandomNumber(min, max) { | |
min = Math.ceil(min); | |
max = Math.floor(max); | |
return Math.floor(Math.random() * (max - min + 1)) + min; | |
} | |
</script> | |
</body> | |
</html> |