Last active
December 15, 2015 02:59
-
-
Save pnavarrc/5190856 to your computer and use it in GitHub Desktop.
Example of Drag Behavior in D3
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 lang="en"> | |
<head> | |
<meta charset="utf-8"> | |
<title>Drag Behavior Demo</title> | |
</head> | |
<script src="http://d3js.org/d3.v3.min.js"></script> | |
<body> | |
<script type="text/javascript"> | |
var width = 600, | |
height = 600, | |
div = d3.select('body').append('div'), | |
svg = div.append('svg'), | |
bar = svg.append('rect'), | |
drag = d3.behavior.drag(); | |
svg.attr('width', width) | |
.attr('height', height); | |
// This function is called on drag | |
function move(d) { | |
var bar = d3.select(this); | |
// Update the position of the bar by adding the drag distance in each coordinate | |
bar.attr('x', parseInt(bar.attr('x'), 10) + d3.event.dx) | |
.attr('y', parseInt(bar.attr('y'), 10) + d3.event.dy); | |
} | |
drag.origin(Object) | |
.on('drag', move); | |
bar = svg.append('rect'), | |
bar.attr('x', (width - 200) / 2) | |
.attr('y', (height - 200) / 2) | |
.attr('width', 200) | |
.attr('height', 200) | |
.attr('fill', '#98CFEA') | |
.call(drag); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment