Skip to content

Instantly share code, notes, and snippets.

@dobbs
Forked from mbostock/.block
Last active August 29, 2015 14:05
Show Gist options
  • Save dobbs/1d353282475013f5c156 to your computer and use it in GitHub Desktop.
Save dobbs/1d353282475013f5c156 to your computer and use it in GitHub Desktop.

Mouseover to repel nodes. Adapted from an adaptation of Mike Bostock's talk on force layouts.

Trying to get collision detection of rectangular objects.

pageWidth = 820
pageHeight = 600
nodes = d3.range(200).map(->
node =
x: Math.random() * (pageHeight - 40) + 20
y: Math.random() * (pageWidth - 40) + 20
width: (Math.random() * 5 + 3) * 9
height: 18
x2: -> node.x + node.width
y2: -> node.y + node.height
)
root = nodes[0]
root.fixed = true
color = d3.scale.category10();
force = d3.layout.force()
.gravity(0.05)
.charge((d,i) -> if i then -40 else -2000)
.nodes(nodes)
.size([pageWidth, pageHeight])
.start()
svg = d3.select("body").append("svg")
.attr("width", pageWidth)
.attr("height", pageHeight)
svg.selectAll("rect")
.data(nodes.slice 1)
.enter().append("rect")
.attr("width", (d)->d.width)
.attr("height", (d)->d.height)
.style("fill", (d, i) -> color(i % 3))
overlap = (a, b) ->
(a.x < b.x < a.x2() and a.y < b.y < a.y2()) or
(a.x < b.x2() < a.x2() and a.y < b.y2() < a.y2())
collide = (node) ->
padding = 32
nx1 = node.x - padding
nx2 = node.x2() + padding
ny1 = node.y - padding
ny2 = node.y2() + padding
(quad, x1, y1, x2, y2) ->
if (quad.point and (quad.point isnt node))
if overlap(node, quad.point)
dy = Math.min(
node.y2() - quad.point.y,
quad.point.y2() - node.y)/2
node.y -= dy
quad.point.y += dy
x1 > nx2 or x2 < nx1 or y1 > ny2 or y2 < ny1
force.on "tick", (e) ->
q = d3.geom.quadtree(nodes)
q.visit(collide node) for node in nodes
svg.selectAll("rect")
.attr("x", (d)->d.x)
.attr("y", (d)->d.y)
svg.on "mousemove", ->
p1 = d3.mouse(this)
root.px = p1[0]
root.py = p1[1]
force.resume()
#Copyright 2014 Eric Dobbs
#
#Licensed under the Apache License, Version 2.0 (the "License");
#you may not use this file except in compliance with the License.
#You may obtain a copy of the License at
#
#http://www.apache.org/licenses/LICENSE-2.0
#
#Unless required by applicable law or agreed to in writing, software
#distributed under the License is distributed on an "AS IS" BASIS,
#WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#See the License for the specific language governing permissions and
#limitations under the License.
<!DOCTYPE html>
<meta charset="utf-8">
<body>
<script src="//cdnjs.cloudflare.com/ajax/libs/coffee-script/1.7.1/coffee-script.min.js"></script>
<script src="//d3js.org/d3.v3.min.js"></script>
<script src="code.coffee" type="text/coffeescript"></script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment