Last active
August 29, 2015 14:27
-
-
Save plmrry/499615d333815efaa165 to your computer and use it in GitHub Desktop.
Particle Experiments
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> | |
<html> | |
<head> | |
<script src="http://d3js.org/d3.v3.min.js"></script> | |
<meta charset="utf-8"> | |
</head> | |
<body> | |
<script src="script.js"></script> | |
</body> | |
</html> |
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
var margin = { top: 50, left: 50, bottom: 50, right: 50 }, | |
width = 700 - margin.left - margin.right, | |
height = 500 - margin.top - margin.bottom; | |
var canvas = d3.select('body') | |
.append('canvas') | |
.attr({ | |
width: width, | |
height: height | |
}) | |
.style({ | |
position: 'absolute', left: margin.left, top: margin.top | |
}) | |
.node().getContext('2d'); | |
var main = d3.select("body").append("svg") | |
.style({ | |
width: width + margin.left + margin.right, | |
height: height + margin.top + margin.bottom, | |
position: 'absolute', top: 0, left: 0 | |
}) | |
.append("g") | |
.attr({ | |
transform: "translate(" + [margin.left, margin.top] + ")" | |
}); | |
main.append("rect").attr({ | |
width: width, height: height, fill: "none", | |
}); | |
var n = 100; | |
var random = d3.random.normal(); | |
function newData() { return { x: random(), y: random(), vel: 0, accel: 0 }; } | |
var data = d3.range(n).map(newData); | |
var x = d3.scale.linear() | |
.domain(d3.extent(data, function(d) { return d.x; })) | |
.range([0, width]); | |
var y = d3.scale.linear() | |
.domain(d3.extent(data, function(d) { return d.y; })) | |
.range([height, 0]); | |
var rate = 2.0, sample = n * 0.5; | |
var random2 = d3.random.normal(Math.floor(sample), 10); | |
d3.timer(function() { | |
if (random() > rate) { | |
console.log(Math.floor(random2())); | |
var numTargets = Math.floor(random2()); | |
} | |
data.forEach(function(d) { | |
d.vel += random() * 0.01 - d.vel * 0.05 - d.x * 0.01; | |
d.x += d.vel; | |
}); | |
redraw(); | |
}); | |
function redraw() { | |
drawWithCanvas(); | |
} | |
function drawWithCanvas() { | |
canvas.clearRect(0, 0, width, height); | |
canvas.beginPath(); | |
var i = -1, cx, cy; | |
while (++i < data.length) { | |
d = data[i]; | |
cx = x( d.x ); | |
cy = y( d.y ); | |
canvas.moveTo(cx, cy); | |
canvas.arc(cx, cy, 3, 0, 2 * Math.PI); | |
} | |
canvas.fill(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment