Skip to content

Instantly share code, notes, and snippets.

@amitp
Created July 30, 2014 15:05
Show Gist options
  • Save amitp/4efb40e97eee561145b8 to your computer and use it in GitHub Desktop.
Save amitp/4efb40e97eee561145b8 to your computer and use it in GitHub Desktop.
Drag and drop line endpoints example for nodweber
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Besier Curve</title>
<style>
circle {
cursor: pointer;
}
circle:hover {
fill : yellow;
}
line {
stroke : black;
stroke-width: 1;
}
</style>
</head>
<body>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script>
var bodyDom = d3.select('body'),
svgWidth = 800,
svgHeight = 800;
var svg = bodyDom.append('svg')
.attr('width', svgWidth)
.attr('height', svgHeight);
var Points = [
{ control1 : [ 20, 20 ], control2 : [ 20, 80 ] },
{ control1 : [ 50, 50 ], control2 : [ 80, 100 ] },
{ control1 : [ 120, 130 ], control2 : [ 180, 240 ]}
];
var drag = d3.behavior.drag()
.origin(function (d) {
var circle = d3.select(this);
//convert data to DRAG expected data
return { x : circle.attr('cx'), y : circle.attr('cy'), data : d };
})
.on('drag', function (d, i) {
var circle = d3.select(this),
name = circle.attr('name');
//Update Points
d[name][0] = d3.event.x;
d[name][1] = d3.event.y;
updatePoints();
});
function makePoints() {
function setup(group) {
group.append('line');
group.append('circle').attr('name', "control1");
group.append('circle').attr('name', "control2");
var styles = {
fill : '#ccc',
stroke : 'blue',
strokeWidth : 1,
radius : 5
};
group.selectAll('circle')
.attr('fill', styles.fill)
.attr('stroke', styles.stroke)
.attr('stroke-width', styles.strokeWidth)
.attr('r', styles.radius)
.call(drag);
}
svg.selectAll('g').data(Points)
.enter().append('g')
.call(setup);
}
function updatePoints() {
var groups = d3.selectAll("g");
groups.selectAll("line")
.attr('x1', function (d) { return d.control1[0] })
.attr('y1', function (d) { return d.control1[1] })
.attr('x2', function (d) { return d.control2[0] })
.attr('y2', function (d) { return d.control2[1] });
groups.selectAll("circle")
.attr('cx', function (d) { return d[d3.select(this).attr('name')][0]; })
.attr('cy', function (d) { return d[d3.select(this).attr('name')][1]; })
}
makePoints();
updatePoints();
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment