Skip to content

Instantly share code, notes, and snippets.

@shimizu
Last active August 31, 2015 06:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shimizu/82070184834ac5f9607b to your computer and use it in GitHub Desktop.
Save shimizu/82070184834ac5f9607b to your computer and use it in GitHub Desktop.
D3 drag behavior example

ドラッグに追従するサークル群

<!DOCTYPE html>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<title>D3 drag behavior example</title>
<style>
html, body, svg {
width: 100%;
height: 100%;
padding: 0px;
margin: 0px;
}
</style>
<body>
<button id="reset">reset</button>
<svg></svg>
<script src="//cdnjs.cloudflare.com/ajax/libs/d3/3.5.5/d3.min.js"></script>
<script>
var svg = d3.select('svg');
var dataSet = d3.range(100);
var wRange = 960;
var hRange = 500;
var circle = svg.selectAll("circle")
.data(dataSet)
.enter()
.append('circle')
.attr({
'width':100,
'height':30,
'fill': 'blue',
'fill-opacity':0.5,
'r': function(){ return ( Math.random() * 15 ) + 4 },
'cx':function(){ return Math.floor(Math.random() * wRange )},
'cy':function(){ return Math.floor(Math.random() * hRange )}
});
var drag = d3.behavior.drag()
.on("drag", function(){
circle
.transition()
.delay(function(d,i){ return i * 100 })
.attr({
'cx':d3.event.x,
'cy':d3.event.y
})
});
circle.call(drag);
d3.select("#reset").on('click', function(){
circle.transition()
.attr({
'cx':function(){ return Math.floor(Math.random() * wRange )},
'cy':function(){ return Math.floor(Math.random() * hRange )}
})
})
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment