Some visual changes to Mike Bostock's Canvas Swarm example.
-
-
Save steveharoz/f84b9c1efd8c3a7256c0e20665900926 to your computer and use it in GitHub Desktop.
Canvas Swarm
This file contains hidden or 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
license: gpl-3.0 |
This file contains hidden or 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"> | |
<title>Canvas Swarm</title> | |
<style> | |
body { | |
background: darkred; | |
} | |
canvas { | |
position: absolute; | |
top: 0; | |
} | |
</style> | |
<div id="fps">FPS: <span>?</span></div> | |
<script src="http://d3js.org/d3.v3.min.js"></script> | |
<script> | |
var data = d3.range(1000).map(function() { | |
return {xloc: 0, yloc: 0, xvel: 0, yvel: 0}; | |
}); | |
var width = 960, | |
height = 500, | |
angle = 2 * Math.PI; | |
var x = d3.scale.linear() | |
.domain([-5, 5]) | |
.range([0, width]); | |
var y = d3.scale.linear() | |
.domain([-5, 5]) | |
.range([0, height]); | |
var time0 = Date.now(), | |
time1; | |
var fps = d3.select("#fps span"); | |
var canvas = d3.select("body").append("canvas") | |
.attr("width", width) | |
.attr("height", height); | |
var context = canvas.node().getContext("2d"); | |
context.fillStyle = "white"; | |
context.strokeStyle = "#F00"; | |
context.strokeWidth = 1; | |
d3.timer(function() { | |
context.clearRect(0, 0, width, height); | |
data.forEach(function(d,i) { | |
d.xloc += d.xvel; | |
d.yloc += d.yvel; | |
d.xvel += 0.04 * (Math.random() - .5) - 0.05 * d.xvel - 0.0005 * d.xloc; | |
d.yvel += 0.04 * (Math.random() - .5) - 0.05 * d.yvel - 0.0005 * d.yloc; | |
context.beginPath(); | |
context.arc(x(d.xloc), y(d.yloc), Math.min(1 + 1000 * Math.abs(d.xvel * d.yvel), 10), 0, angle); | |
context.fillStyle = i % 2 ? "white" : "black"; | |
context.fill(); | |
//context.stroke(); | |
}); | |
time1 = Date.now(); | |
fps.text(Math.round(1000 / (time1 - time0))); | |
time0 = time1; | |
}); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment