ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

Designing Bezier Curves with Javascript and jQuery - Part 2 in a series

Updated on April 4, 2011

a designed curve

discussion of Bezier curves

Third degree polynomials can be used do describe a wide range of different smooth curves between two points.  The trick is in finding the correct coefficients for the polynomials that describes the curve you want.  (There is one polynomial per dimension.  Here one for x and one for y. )  What is depicted here is a visual method for computing the coefficients.  The resulting polynomials are a compact way to describe the curve, you selected.

What is specified are the two end points of the curve, and the first derivative at each end point.  The derivatives are sometimes called control points, because their effect is to pull the curve towards the selected point.  All specifications are done with a click of the mouse.

From a programming point of view, drawing these curves requires recording a sequence of actions the user does, then manipulating the DOM (document object model) to render the result.  In the first hub in this series I covered using jQuery to collect the mouse input.  In this hub, I will use jQuery to manipulate the DOM and take actions on behalf of the user.

the control logic

function jgbezier ( drawarea ) {
	var bpoints = new Array();
	var bpointcnt = 0;
	unitsquare.dontscale = true;
	$( "#mousetarget" ).bind( "click", function (e) {
		if( bpointcnt < 4 ) {
			bpoints[bpointcnt] = drawarea.screenCoordinatesToPoint( e.clientX, e.clientY 

);
			++bpointcnt;
			if( bpointcnt == 4 ) {
				//draw curve
				var xpath = genbezierequation( bpoints[0].x, bpoints[1].x - bpoints

[0].x, bpoints[2].x, bpoints[2].x - bpoints[3].x );
				var ypath = genbezierequation( bpoints[0].y, bpoints[1].y - bpoints

[0].y, bpoints[2].y, bpoints[2].y - bpoints[3].y );	
				$( "#xformula" ).attr( "value", xpath );
				$( "#yformula" ).attr( "value", ypath );
				$( "#jgmeshstart" ).attr( "value", '0' );
				$( "#jgmeshend" ).attr( "value", '1' );
				$( "#start_calc" ).trigger( "click" );
			}
		}
	});
}

discussion of code logic

This function is invoked by a new button on the graphing calculator of my previous series of hubs.   It first uses jQuery to register itself to also receive mouse click events on the drawing area, nothing new there.  It uses a closure to record the events that it receives until it gets to four clicks.  Then it fills in the user input fields of the graphing calculator and clicks the "graph" button.

I could have used native javascript to do all of this, after all jQuery is just a great, big javascript function, but jQuery makes my code simpler and more elegant.

$( <target> ).attr( <attribute>, <value> ) is a lot more direct and self-explanatory way to set the value of an HTML tag's attribute than the equivalent, hand-crafted DOM navigation, for example.   I also use jQuery's trigger method to click the"graph" button.

Calculating the polynomial coefficients

function genbezierequation( x0, fx0, x1, fx1 ){
	var a;
	var b;
	var c;
	var d;

	a = x0;
	b = fx0;
	c =  -3 * x0 - 2 * fx0 + 3 * x1 - fx1;
	d = fx1 - 2 * x1 + 2 * x0 + fx0;

	var rval = a + " + x * " + b +  " + x * x * " + c + " + x * x * x * " + d;
	return( rval );
}

Bezier guts explicated

A third degree polynomial is of the form: f(x) = a + bx + cx2 + dx3

The first derivative of this polynomial is f'(x) = b + 2cx + 3dx2

The user will specify f(0), f'(0), f(1) and f'(1) with their clicks. This provides four equations which can be used to solve for the four unknowns a, b, c and d, in terms of f(0), f'(0), f(1) and f'(1). The function above uses the formula from this solution to calculate the coefficients that correspond to a specific set of mouse clicks. The rest is just some syntactic sugar to make javascript happy.

some mechanics for calculating graph points from screen points

function scjgpt( sx, sy ) {
	var rval = new jgpoint();
	rval.x = this.x0 + (( this.x1 - this.x0 )/(this.screenx1 - this.screenx0)) * ( sx - 

this.screenx0 );
	rval.y = this.y0 + (( this.y1 - this.y0 )/(this.screeny1 - this.screeny0)) * ( sy - 

this.screeny0 );
	return( rval );
}

var jgcoordinatesbase = {
	x0: -1.25,
	screenx0: 50,
	y0: -1.25,
	screeny0: 450,
	x1: 1.25,
	screenx1: 450,
	y1: 1.25,
	screeny1: 50,
	dontscale: false,
	pointToScreenCoordinates: jgptsc,
	screenCoordinatesToPoint: scjgpt,
...

some required mechanics

The only other code that I had to add to my graphing calculator, was a subroutine that converts the screen coordinates, provided by the mouse click event, to the coordinates of my graph.

Notes:

The derivative at f'(1) is actually specified by giving the negative of the actual derivative used in the computation.  This is a notational convenience that makes the control points behave symmetrically from the user's point of view.

I had to add support for unary minus to my expression parsing code and fix a bug with the handling of the last term to get this code to work.  ( What?  Me write a bug? :=)

Next hub in this series, I will try to make the setting of the points more animated.

another designed curve

working

This website uses cookies

As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://corp.maven.io/privacy-policy

Show Details
Necessary
HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
LoginThis is necessary to sign in to the HubPages Service.
Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
AkismetThis is used to detect comment spam. (Privacy Policy)
HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
Features
Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
MavenThis supports the Maven widget and search functionality. (Privacy Policy)
Marketing
Google AdSenseThis is an ad network. (Privacy Policy)
Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
Index ExchangeThis is an ad network. (Privacy Policy)
SovrnThis is an ad network. (Privacy Policy)
Facebook AdsThis is an ad network. (Privacy Policy)
Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
AppNexusThis is an ad network. (Privacy Policy)
OpenxThis is an ad network. (Privacy Policy)
Rubicon ProjectThis is an ad network. (Privacy Policy)
TripleLiftThis is an ad network. (Privacy Policy)
Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
Statistics
Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)
ClickscoThis is a data management platform studying reader behavior (Privacy Policy)