Created
July 30, 2014 13:33
-
-
Save nodech/a31b167204290d1ef88d to your computer and use it in GitHub Desktop.
How to update this data and redraw everything properly ? )
This file contains hidden or 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> | |
<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 | |
Points[i][name][0] = d3.event.x; | |
Points[i][name][1] = d3.event.y; | |
drawPoints(); | |
}); | |
function drawPoints() { | |
var initData = svg.selectAll('g').data(Points), | |
pointGroup = initData.enter().append('g'), | |
remove = initData.exit().remove(); | |
var ctrlLines1 = pointGroup.append('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] }); | |
var ctrlPoint1 = controlStyles(pointGroup.append('circle'), 'control1'); | |
var ctrlPoint2 = controlStyles(pointGroup.append('circle'), 'control2'); | |
function controlStyles(ctrlPoint, pointName) { | |
var styles = { | |
fill : '#ccc', | |
stroke : 'blue', | |
strokeWidth : 1, | |
radius : 5 | |
}; | |
ctrlPoint | |
.attr('name', pointName) | |
.attr('fill', styles.fill) | |
.attr('stroke', styles.stroke) | |
.attr('stroke-width', styles.strokeWidth) | |
.attr('r', styles.radius) | |
.attr('cx', function (d) { return d[pointName][0]; }) | |
.attr('cy', function (d) { return d[pointName][1]; }) | |
.call(drag); | |
return ctrlPoint; | |
} | |
} | |
drawPoints(); | |
function extend(base, data) { | |
for (var key in data) { | |
base[key] = data[key]; | |
} | |
return base; | |
} | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment