Color Representation and Gradients

Part 3: Creating Our Own Gradients

In this part we will create for ourselves another way to form gradients.

Contents

Part 1: RGB and HSL

  1. Representing Colors
  2. Defining HSL
  3. Deriving HSL

Part 2: Gradients

  1. What a Gradient Is
  2. Difficulties with HSL Paths
  3. Fixing HSL Paths

Part 3: Creating Our Own Gradients

  1. The Idea
  2. The Derivation
  3. Creating Paths
  4. The Implementation

The Idea

The general idea of our new way of forming gradients is to take straight-line paths in the HSL cylinder. The gradients we went over in part 2 would form Archimedean spirals in the HSL cylinder, but our new gradient will be simple straight lines through the cylinder.

Despite lines being more geometrically simple, the way HSL is represented lends itself more naturally to spiral gradients, so we will have to convert the representation of HSL into a more traditional representation using three orthogonal (perpenicular) coordinates. We will call this representation XYZ space, because we are very creative.

The Derivation

In the cylindrical model for HSL, hue represents the angle, saturation the radius, and lightness the height of a point in the cylinder. We will impose a rectangular coordinate system with the following conditions:

From these definitions quite simple derivations for XYZ space emerge (at least, if you recall your trigonometry). They are as follows:

Now that we have derived actual numbers to represent our space, we can now create a method to compute paths in it.

Creating Paths

Fortunately, the work has already been done. Our new space is rectangular, so it doesn't have the same problems as HSL with periodicity or non-unique representations. Rather, the method used to compute paths in RGB space works perfectly for this new space, so we can simply adopt it without modification.

To actually implement this there is one more thing we have to do, however. XYZ space will obviously not have any support in CSS or anywhere else, so after we compute paths in XYZ we will then need to re-convert the points into HSL. We could also convert it into RGB, but this would be quite difficult.

To do this, we use the following formulae for saturation and lightness:

Where sqrt is the square-root function.

For hue we can use h = arctan(y / x) / 2π, but this will map hue to the interval (-.5, .5). To deal with negative values, we simply add 1 to h if h < 0.

This allows to actually implement our path using CSS.

The Implementation

Here you can see all the various gradients side by side:

RGB

HSL

XYZ