Skip to content

Instantly share code, notes, and snippets.

@nstrayer
Last active November 9, 2016 04:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nstrayer/a0abfffcf3ead04268df78b8def34b62 to your computer and use it in GitHub Desktop.
Save nstrayer/a0abfffcf3ead04268df78b8def34b62 to your computer and use it in GitHub Desktop.
Playing with a new intro to my website

An animated random walk using a uniform distribution to decide the angle of departure.

<!DOCTYPE html>
<meta charset="utf-8">
<style>
.link {
fill: none;
stroke-width: 1.5px;
}
.axis, .node {
stroke: #000;
stroke-width: 1.5px;
}
.line {
fill:none;
}
</style>
<body>
<script src="//d3js.org/d3.v4.min.js"></script>
<script>
var width = 960,
height = 500;
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
.append("g")
// .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");
//Random walks!
var number_of_steps = 5000;
var number_of_directions = 5;
var start_point = [{x: 0, y: 0}];
var step_length = 5;
function nextStep(current) {
var pi = 3.1415926;
var theta = Math.random() * (2 * pi);
var x_direction = Math.cos(theta) * step_length;
var y_direction = Math.sin(theta) * step_length;
return {x: current.x + x_direction, y: current.y + y_direction}
}
function go_walking(i, num_steps, walk){
if(i < num_steps){
walk.push(nextStep(walk[i]));
go_walking(i+1, num_steps, walk);
}
return(walk);
}
var ourWalk = go_walking(0,number_of_steps, start_point);
//ourWalk.forEach((w) => console.log(w.x));
//draw
// The d3 stuff
var biggest_x = d3.max(ourWalk, (v) => Math.abs(v.x))
var biggest_y = d3.max(ourWalk, (v) => Math.abs(v.y))
console.log(biggest_y)
var x = d3.scaleLinear()
.domain([-biggest_x, biggest_x])
.range([0, width]);
var y = d3.scaleLinear()
.domain([-biggest_y, biggest_y])
.range([height, 0]);
var line = d3.line()
.x(function(d) { return x(d.x); })
.y(function(d) { return y(d.y); });
svg.append("path")
.datum(ourWalk)
.attr("class", "line")
.attr("d", line)
.style("stroke-width", 1)
.style("stroke", "steelblue")
.style("opacity", 1)
var animateWalk = function() {
// Get the length of each line in turn
var totalLength = d3.select(".line").node().getTotalLength();
d3.selectAll(".line")
.style("opacity", "0.5")
.attr("stroke-dasharray", totalLength + " " + totalLength)
.attr("stroke-dashoffset", totalLength)
.transition()
.duration(10000)
// .ease("quad")
.attr("stroke-dashoffset", 0)
.style("stroke-width",1)
/* intro
.transition()
.duration(800)
.attr("fill-opacity", 0)
.each("end", function(){
writeGreeting()
// title
// .transition()
// .duration(1800)
// .delay(800)
// .attr("fill-opacity", 0.65)
}) */
}
animateWalk();
console.log("hello.")
console.log("everything worked!")
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment