Bézier curves d3
by jarandaf
CSS
svg {
background-color: grey;
}
path {
stroke: red;
stroke-width: 1px;
fill: none;
}
JavaScript
function Point(x, y){
this.x = x;
this.y = y;
};
var linearBezier = function(p1, p2){
var t = d3.range(0, 1, .01);
var points = [];
t.forEach(function (step) {
var x = p1.x*(1-step) + step*p2.x;
var y = p1.y*(1-step) + step*p2.y;
points.push(new Point(x, y));
});
return points;
};
var quadraticBezier = function(p1, p2, p3){
var t = d3.range(0, 1, .01);
var points = [];
t.forEach(function (step) {
var x = Math.pow(1-step, 2)*p1.x + 2*step*(1-step)*p2.x + Math.pow(step,2)*p3.x;
var y = Math.pow(1-step, 2)*p1.y + 2*step*(1-step)*p2.y + Math.pow(step,2)*p3.y;
points.push(new Point(x,y));
});
return points;
};
var cubicBezier = function(p1, p2, p3, p4){
var t = d3.range(0, 1, .01);
var points = [];
t.forEach(function (step) {
var x = Math.pow(1-step, 3)*p1.x + 3*p2.x*step*Math.pow(1-step, 2) + 3*p3.x*Math.pow(step,2)*(1-step) + p4.x*Math.pow(step,3);
var y = Math.pow(1-step, 3)*p1.y + 3*p2.y*step*Math.pow(1-step, 2) + 3*p3.y*Math.pow(step,2)*(1-step) + p4.y*Math.pow(step,3);
points.push(new Point(x,y));
});
return points;
}
var width = height = 500;
var x = d3.scale.linear().domain([0,27]).range([0, width]);
var y = d3.scale.linear().domain([0,25]).range([height, 0]);
var line = d3.svg.line()
.interpolate("basis")
.x(function(d) { return x(d.x); })
.y(function(d) { return y(d.y); });
//var data = linearBezier(new Point(1,2), new Point(7,8));
//var data = quadraticBezier(new Point(1,2), new Point(20,15), new Point(22, 2));
var data = cubicBezier(new Point(0,0), new Point(0,20), new Point(27, 0), new Point(27, 20));
d3.select('body').append('svg')
.attr('width', 500)
.attr('height', 500)
.datum(data)
.append('path')
.attr('d', function (d) { return line(d); });