Posted by: pixelero | April 27, 2011

SplineGradient – HTML5 Experiment

This is very similar to my previous post. It’s also deals with putting some extra effect to a spline curve, and it even shares some of the source codes. I got the idea for this from some Mathematica demonstrations with catacaustics, or ‘a curve formed by light reflecting from a curved surface. The principle there is so simple, just draw tangents of some curve, yet I find the results so beautifully surprising.
I wanted to come up with something similar, but having a smoother shading, instead of consisting of seperate lines.

Click the images above to see the demo. You can drag the controls on canvas (they might seem a bit sticky I know), and try changing the parameters.

The principle here is to generate a mesh of triangles along the curve, and render a linear gradient on each triangle. The densier the mesh, the smoother the result looks. Ok, there are still some fan-like clearly visible lines – those seemed a bit too complex to remove. Changing the coordinate orientation by a triangle’s three vertices in javascript is quite simple. This is how context.setTransform(x0,y0, x1,y1, tx,ty) aligns the coordinate system: Point (tx,ty) becomes the new origin (0,0), x-axis sets in direction (x0,y0) and y in direction (x1,y1).

Some example of code using this class:

// canvas = canvas element placed in html
context = canvas.getContext('2d');
if (!context) return; 

// Define a gradient
var gradient = context.createLinearGradient(0,0, 0,1);
gradient.addColorStop(0.0, 	'rgba(255,255,255, 1)');
gradient.addColorStop(1.0, 	'rgba(255,255,255, 0)');

// Define the splineGradient-object
var splineGradient = new SplineGradient(context, gradient);

// Set the angle and offsets from center axis
splineGradient.angle = Math.random()*Math.PI/2;
splineGradient.offset1 = 0;
splineGradient.offset2 = 1;

// And start drawing, methods are similar to javascript for canvas element
splineImage.moveTo(x0, y0);
splineImage.bezierCurveTo(x1,y1, x2,y2, x3,y3);

… I’ll be back, probably next time with some flash/pixel bender stuff.


  1. This seems like a step towards the Bezier mesh that is used in Illustrator. Very cool demo indeed. I’ve always loved your work, I’m glad to see you’ve found some free time to do some personal projects 🙂 Great work!

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s


%d bloggers like this: