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

« 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]


   1  
   2  //+ Jonas Raoni Soares Silva
   3  //@ http://jsfromhell.com/math/bezier [v1.0]
   4  
   5  function Bezier(p0, p1, c0, c1){//v1.0
   6  	var o = this;
   7  	o.x0 = p0.x, o.y0 = p0.y, o.x1 = p1.x, o.y1 = p1.y,
   8  	o.cx0 = c0.x, o.cy0 = c0.y, o.cx1 = c1.x, o.cy1 = c1.y;
   9  };
  10  with({$: Bezier, o: Bezier.prototype}){
  11  	$.point = function(x, y){
  12  		return {x: x, y: y};
  13  	};
  14  	o.getCoordinates = function(t){
  15  		var i = 1 - t, x = t * t, y = i * i, a = x * t,
  16  		b = 3 * x * i, c = 3 * t * y, d = y * i, o = this;
  17  		return Bezier.point(a * o.x0 + b * o.cx0 + c * o.cx1 + d * o.x1,
  18  		a * o.y0 + b * o.cy0 + c * o.cy1 + d * o.y1);
  19  	};
  20  	o.plot = function(c){
  21  		var r, x = (x = this.x0 - this.x1) * x, y = (y = this.y0 - this.y1) * y,
  22  		l = l = Math.ceil(Math.sqrt(x + y)), i = l + 1;
  23  		while(c(this.getCoordinates(r = --i / l), r), i);
  24  	};
  25  }



Usage

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