Skip to content

Instantly share code, notes, and snippets.

@nswarr
Created October 23, 2012 03:51
Show Gist options
  • Save nswarr/3936516 to your computer and use it in GitHub Desktop.
Save nswarr/3936516 to your computer and use it in GitHub Desktop.
Adds circles to the force layout to test the performance
#=require d3-helper
width = $(window).width() - 20
height = $(window).height() - 10
radius_scale = d3.scale.pow().exponent(0.5).domain([0, 100]).range([2, 20])
center = {x: width / 2, y: height / 2}
nodes = []
ticks = 0
layout_gravity = -0.01
damper = 0.1
vis = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
.attr("id", "svg_vis")
tps = vis.append("text")
.attr("font-size", 40)
.attr("x", 40)
.attr("y", 80)
.style("fill", "black")
text = vis.append("text")
.attr("font-size", 40)
.attr("x", 40)
.attr("y", 130)
.style("fill", "black")
bubbles = vis.selectAll("circle").data(nodes)
force = d3.layout.force()
.size([width, height])
.gravity(layout_gravity)
.charge((d) -> -Math.pow(d.radius, 2.0) / 8)
.friction(0.9)
.on "tick", (e) =>
++ticks
bubbles.each(move_towards_center(e.alpha))
.attr("transform", (d) -> "translate(" + d.x + "," + d.y + ")")
move_towards_center = (alpha) =>
(d) =>
d.x = d.x + (center.x - d.x) * (damper + 0.02) * alpha
d.y = d.y + (center.y - d.y) * (damper + 0.02) * alpha
#` this`.cx.baseVal.value = d.x
#` this`.cy.baseVal.value = d.y
addNode = ->
for i in [0...100]
val = 100 * Math.random()
nodes.push {
x: width * Math.random()
y: height * Math.random()
val: val.toFixed(0)
radius: radius_scale(val)
}
bubbles = vis.selectAll(".bubble")
.data(nodes)
newBubbles = bubbles.enter().append("g").attr("class", "bubble")
appendBubbles(newBubbles) if bubblesShown
appendText(newBubbles) if textShown
force.nodes(nodes)
force.start()
text.text(nodes.length + " bubbles")
appendText = (context) ->
context
.append("text")
.text((d) -> d.val)
.attr("font-size", (d) -> (d.radius * 0.8) + "px" )
.attr("text-anchor", "middle")
.style("fill", "black")
appendBubbles= (context) ->
context
.append("circle")
.attr("r", (d) -> radius_scale(d.val))
.attr("fill", (d) => D3Helper.randomColor())
.attr("stroke-width", 2)
.attr("stroke", (d) => D3Helper.randomColor())
.attr("id", (d) -> "bubble_#{d.id}")
force.start()
setInterval(->
addNode() unless paused
, 3000)
setInterval(->
if ticks > 0
tps.text( ticks * 4 + " tps")
ticks = 0
, 250)
paused = false
window.pause = () ->
paused = !paused
textShown = true
window.toggleText = () =>
textShown = !textShown
if textShown
appendText(vis.selectAll(".bubble"))
else
vis.selectAll(".bubble text").remove()
bubblesShown = true
window.toggleBubbles = () =>
bubblesShown = !bubblesShown
if bubblesShown
appendBubbles(vis.selectAll(".bubble"))
else
vis.selectAll(".bubble circle").remove()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment