Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

About this user

Jonas Raoni Soares Silva http://www.jsfromhell.com

« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS 

Bézier Curve //JavaScript Class


Calculates the points for a bézier curve.

[UPDATED CODE AND HELP CAN BE FOUND HERE]


//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com/math/bezier [v1.0]

function Bezier(p0, p1, c0, c1){//v1.0
	var o = this;
	o.x0 = p0.x, o.y0 = p0.y, o.x1 = p1.x, o.y1 = p1.y,
	o.cx0 = c0.x, o.cy0 = c0.y, o.cx1 = c1.x, o.cy1 = c1.y;
};
with({$: Bezier, o: Bezier.prototype}){
	$.point = function(x, y){
		return {x: x, y: y};
	};
	o.getCoordinates = function(t){
		var i = 1 - t, x = t * t, y = i * i, a = x * t,
		b = 3 * x * i, c = 3 * t * y, d = y * i, o = this;
		return Bezier.point(a * o.x0 + b * o.cx0 + c * o.cx1 + d * o.x1,
		a * o.y0 + b * o.cy0 + c * o.cy1 + d * o.y1);
	};
	o.plot = function(c){
		var r, x = (x = this.x0 - this.x1) * x, y = (y = this.y0 - this.y1) * y,
		l = l = Math.ceil(Math.sqrt(x + y)), i = l + 1;
		while(c(this.getCoordinates(r = --i / l), r), i);
	};
}



Usage

var bezier = new Bezier(Bezier.point(0, 50), Bezier.point(100, 20), Bezier.point(50, 0), Bezier.point(50, 50));
bezier.plot(function(p, r){
	document.write("x: ", p.x >> 0, " y: ", p.y >> 0, " at ", (r * 100).toFixed(1), "%<br />");
});
« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS