Example illustrating the use of d3-force-attract
with a dynamic attract target
.
Last active
November 15, 2016 06:55
-
-
Save ericsoco/7eebab15da4bb1040977da508aebbff6 to your computer and use it in GitHub Desktop.
d3-force-attract I
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> | |
<title>d3-force-attract: mouse attract</title> | |
</head> | |
<body> | |
<script src="https://d3js.org/d3.v4.min.js"></script> | |
<script src="https://unpkg.com/d3-force-attract@latest"></script> | |
<script> | |
var width = 960, | |
height = 500, | |
radius = 20; | |
var nodes = [{ | |
x: width * Math.random(), | |
y: height * Math.random(), | |
r: radius | |
}]; | |
// set up attract force to pull nodes toward mouse location | |
var simulation = d3.forceSimulation() | |
.force('attract', d3.forceAttract() | |
.target([width / 2, height / 2])) | |
.on('tick', layoutTick) | |
.nodes(nodes); | |
var svg = d3.select('body').append('svg') | |
.attr('width', width) | |
.attr('height', height); | |
var node = svg.selectAll('circle') | |
.data(nodes) | |
.enter().append('circle') | |
.attr('cx', function (d) { return d.x; }) | |
.attr('cy', function (d) { return d.y; }) | |
.attr('r', function (d) { return d.r; }); | |
svg.on('mousemove', function () { | |
simulation.force('attract').target(d3.mouse(this)); | |
simulation | |
.alphaTarget(0.3) | |
.restart(); | |
}); | |
function layoutTick (e) { | |
node | |
.attr('cx', function (d) { return d.x; }) | |
.attr('cy', function (d) { return d.y; }); | |
} | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment