Permalink
Switch branches/tags
Nothing to show
Find file
Fetching contributors…
Cannot retrieve contributors at this time
69 lines (56 sloc) 1.64 KB
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1,maximum-scale=1"/>
<title>Drag</title>
<link rel="stylesheet" type="text/css" href="../../css/styles.css"/>
<script type="text/javascript" src="../../lib/d3.js"></script>
<style type="text/css">
svg {
border: 1px solid black;
}
circle {
fill: #dc143c;
}
</style>
</head>
<body>
<script type="text/javascript">
var width = 960, height = 500, r = 50;
var data = [
[width / 2 - r, height / 2 - r],
[width / 2 - r, height / 2 + r],
[width / 2 + r, height / 2 - r],
[width / 2 + r, height / 2 + r]
];
var svg = d3.select("body").append("svg")
.attr("width", width)
.attr("height", height)
.append("g");
var drag = d3.behavior.drag() // <-A
.on("drag", move);
svg.selectAll("circle")
.data(data)
.enter().append("circle")
.attr("r", r)
.attr("transform", function (d) {
return "translate(" + d + ")";
})
.call(drag); // <-A
function move(d) {
var x = d3.event.x, // <-C
y = d3.event.y;
if(inBoundaries(x, y))
d3.select(this)
.attr("transform", function (d) { // <-D
return "translate(" + x + ", " + y + ")";
});
}
function inBoundaries(x, y){
return (x >= (0 + r) && x <= (width - r))
&& (y >= (0 + r) && y <= (height - r));
}
</script>
</body>
</html>