Draw CSS Gradients

Recently I found myself extremely interested in computer graphics. Meanwhile it's time to redesign my portfolio and I decide to make it colorful. Gradient is no doubt the easiest starting point.

Currently there are two types of gradients supported in CSS: linear gradient

Linear Gradient

and radial gradient.

Radial Gradient

Comparing two pictures above you can easily distinguish which is which once you learn the concept of each gradient.

Linear gradient

Suppose there is a rectangle. Let's try to draw a linear gradient step by step.

Let's start from the center of the rectangle which is also the intersection of diagonal. Make it origin and build a coordinate system. Casually draw a line passing from the origin and we call it gradient line. Find two vertices in the same quadrants of the gradient line and passing from them draw two perpendiculars of the gradient line. Call the perpendicular passing from vertex in Quadrant I or II starting point and the other perpendicular ending point. Till now everything is ready to draw the gradient. From starting point to ending point we draw a series of lines with color linear changing by their position. Suppose color of starting point is rgba(r1, g1, b1, a1) and color of ending point is rgba(r2, g2, b2, a2). The distance between starting point and ending point is E and the line we will draw has moved F away from starting point. I guess color of the line will be:

rgba(r1 + (r2-r1)F/E, g1 + (g2-g1)F/E, b1 + (b2-b1)F/E, a1 + (a2-a1)F/E)

Finally we have drawn our linear gradient.

Radial gradient

Radial gradient is more complicated than linear gradient because it has more parameters. Don't worry we will try to draw it from scratch.

Again let's start with a rectangle in a coordinate system. Next we need to choose a shape from ellipse and circle. Circle is just a special kind of ellipse. To make it more common let's choose ellipse. BTW the default value is also ellipse. The shape of our ellipse is always the same with the biggest ellipse inside the rectangle. Then we need to choose a position which will be starting point and the center of our ellipse. After that we need to decide how far our ellipse ends from center. Now from the starting point we draw a series of ellipse towards ending position. The color of each ellipse is determined by how far it has moved, the same with linear gradient. Finally we'll get result.

Conclusion

This is just the very first step of my exploring of computer graphics. In the future I will learn more and share with you guys. Stay tuned.

References