Skip to content

Instantly share code, notes, and snippets.

@max-l
Last active December 10, 2018 18:10
Show Gist options
  • Save max-l/d16139f3d42929feb57f1ac4f2f53529 to your computer and use it in GitHub Desktop.
Save max-l/d16139f3d42929feb57f1ac4f2f53529 to your computer and use it in GitHub Desktop.
sink1
license: mit
<!DOCTYPE html>
<meta charset="utf-8">
<body>
<style>
path {fill: none;stroke: #000;stroke-width: 3px;}
circle {fill: steelblue;stroke: #fff;stroke-width: 1px;}
</style>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script>
const width = 200
const height = 200
const radius = 5
const topLeftX = 130
const topLeftY = 130
const stepDistance = 2
const redrawInterval = 30
var data = [];
var point_count = 10;
var svg = d3.select("body")
.append("svg")
.attr("width", width)
.attr("height", height)
.attr("color", "red")
const rnd = d3.randomUniform(1, 10)
d3.range(point_count).map(i=> {
data.push({
id: i, x:topLeftX, y:topLeftY,
//x: boxLeft, y: boxTop,
slope: rnd() / 10,
x_dir: 1,y_dir: 1,
})
})
redraw(data);
d3.interval(() => redraw(update(data)), redrawInterval)
function redraw(data){
var circle = svg.selectAll("circle")
.data(data, d => d.id)
circle
.attr("r", radius)
.attr("cx", d => d.x)
.attr("cy", d => d.y)
circle.enter().append("circle")
.attr("r", radius)
.attr("cx", d => d.x)
.attr("cy", d => d.y)
}
const update = data =>
data.map(d => calcPointB(d, stepDistance, d.slope))
const getDir = (coord, dir, maxCood, minCoord) =>
(Math.ceil(coord) <= minCoord - radius) ? 1 :
(Math.ceil(coord) >= maxCood - radius) ? -1 : dir
const sqrt = Math.sqrt
const pow2 = a=>Math.pow(a, 2)
const rndDeviation = d3.randomUniform(-1,1)
const calcPointB = (p, d, m) => {
p.x += rndDeviation()
p.y += rndDeviation()
p.x_dir = getDir(p.x, p.x_dir, width, topLeftX);
p.y_dir = getDir(p.y, p.y_dir, height,topLeftY);
p.x = p.x +
(d * sqrt(1 / (1 + pow2(m))) * p.x_dir)
p.y = p.y +
(m * d * sqrt(1 / (1 + pow2(m))) * p.y_dir);
return p;
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment