Approximating a sphere using CSS - and pumpkins!
Tags: 3d, css, geometry, sphere
Published: 2023-11-21 12:52:52

---
title: Approximating a sphere using CSS - and pumpkins!
published: true
date: 2023-11-21 12:55:53 UTC
tags: 3d,css,geometry,sphere
canonical_url:
cover_image:  https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2uydv0sp7qs5xrbw9ev5.png 
---

Before I get to the main topic, please allow me to paint you a more detailed picture of how I got into 3D CSS:

I have been obsessed with 3D graphics all my life. An 80's kid, I'm not sure which I saw first: [TRON](https://www.youtube.com/watch?v=EtyHX7z8fi8&t=8s) or Dire Strait's [Money For Nothing](https://www.youtube.com/watch?v=wTP2RUD_cL0) video, all I know is I was hooked, instantly. I watched the CGI revolution - Jurassic Park and Terminator 2 - with wide eyes and jaw on the floor. I witnessed games boldly fully embracing the third dimension - with the likes of Virtua Fighter and Quake.

Then, of course, is the 3D graphic software - which I didn't devote myself quite as much as I would've liked. Obsessed as I was with CGI as a teen, I didn't pursue it when I got online in the early '00s and suddenly had so many amazing, intuitive tools to pick from. It was only at work that I got into CAD - and while it did allow for some fancy experiments with surfaces, it was mostly for technical applications.

Case in point: to create a sphere you had to draw a semi-circle and spin it around a selected axis:

![A simple demonstration of how a sphere is created in CAD by rotating a semicircle around an axis](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tulb3s87uztzfkjawivg.png)

In contrast, artistic 3D modeling software like Sculptris would allow me to sculpt lifelike statues with tools that felt like actual fingertips:

![A GIF of a 3D model of an orc made using artistic 3D software Sculptris](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2l6r4hytvcqmadgdvoa1.gif)

But just as I was preparing for a deeper dive into 3D art, making my first steps in Blender, I found out that you could do 3D in CSS. Yes, that weird, fascinating and often deeply frustrating thing that you have to use to style your web pages has an intricate system of creating art in three dimensions.

A system that works nothing like Blender - and puts CAD to shame with the number of steps to create even the most basic solid primitive.

Investigating the topic, I stumbled upon this amazing [blog article by Keith Clark](https://keithclark.co.uk/articles/creating-3d-worlds-with-html-and-css/). The man created a 3D FPS in (mostly) plain CSS. Ten years ago! His post details the intricacies of creating cubes and cylinders - to create the staples of boomer shooters: crates and barrels:

![A demonstration of 3D crates (cubes) and barrels and tires (cylinders) from Keith Clark's article linked below](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xl0ugh10ecaigaubpbge.jpg)

(image taken from the blog post, original image URL [here](https://keithclark.co.uk/articles/creating-3d-worlds-with-html-and-css/cssfps-objects.jpg))

All these were created out of plain div elements - the basic building blocks of HTML. You don't get a dedicated "cube" element that you could style. All you have at your disposal is a basic rectangular container - and you assemble 3D shapes by placing a series of appropriately sized containers in 3D space. You have to rotate and push each and every one of them around until they start to resemble the thing.

This got me so fascinated that I forgot all about Sculptris and Blender. The cylinders especially. They weren't perfectly smooth - but close enough.

If that's not good enough for you, look at this circle:

![A polygon of 64 sides that almost looks like a perfect circle if you don't look too closely](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wi6t6nghnee5hxt80gi7.png)

That's not a circle. It's a polygon with 64 sides. It merely approximates a circle.

I started exploring what more I could do from there, given that I took up webdev in 2018, and some things that Keith talked about as the bright future - such as blend modes - were already a fact.

Soon enough, I started thinking: what if I could create more complex shapes - like cones?

Or spheres!

...out of rectangles...

The most obvious idea seemed to be something like the globe from geography class - with a series of parallel horizontal circles, each narrower the farther it is from the equator, and vertical circles all the same size, converging on the poles. Something like this:

![A geometric imitation of a globe, with meridians running from the north to the south pole, and circles of latitude](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/24521hra340deqwl18rv.png)

...except less round or smooth. We're only approximating the sphere - with the crudest shapes possible, imitating the most basic vector graphics. Forget curves and splines. What we're creating will have to look more like this if it's going to run smoothly.

![A simplified, more angular imitation of a globe, with meridians running from the north to the south pole, and circles of latitude ](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yafs11xhp7lvt95285wg.png)

See, HTML and CSS - as powerful as they are on their own these days - aren't exactly Unreal Engine. Whereas the latter can move around millions of polygons, shade and texture them and never break a sweat, your browser might make your CPU sweat with just 100+ objects. And our sphere exceeds that limit. It's based on a 16-gon, which means it consists of 16 slices (like those in an orange), each itself comprised of 8 faces. Our solid, therefore, is made of 128 trapezoid faces - formed by the intersecting meridians and circles of latitude - which, again, we'll have to cut one by one out from rectangular containers, then rotate and push into position using CSS. And math! Lots and lots of math - which is as hard for the CPU as it is for that squishy thing under your skull.

Terrifying and fascinating!

So there I was - and in order to get anywhere from there, some 20 years after high-shool I had to relearn trigonometry. Sines, cosines and the lot. I'll spare you the exact details of figuring out the formulas for what I needed and transplanting the basics of classic geometry onto the constraints of CSS syntax - and PHP, while we're at it - because that's a whole other rabbit hole. Eventually, I was cranking out sphere after sphere. Originally, I would use SVG - which I got really comfortable with - but would eventually transition to clip-path.

For the kicks, I even made one out of borders:

{% codepen https://codepen.io/MackFitz/pen/oNZMXeZ %}

...and (much later) out of conic gradients:

{% codepen https://codepen.io/MackFitz/pen/YzJdKgm %}

This paradigm - a series of trapezoids starting out as triangles at one pole, going via the equator and converging again on the other pole - was neat and intuitive enough, even if I had some slip-ups along the way and needed to rethink the structure a bunch of times. But, as much as I liked it, I had a major issue with it:

The lines converging at the poles meant that the facets that they formed got ever smaller while contributing less and less to the geometry.

This forced me to rethink my approach to the basic shape used for the facet - the trapezoid. I thought of vector graphics - where the basic unit is the triangular vertex, and a trapezoid is just two conjoined vertices combined:

![An illustration of how in vector-based graphics a trapezoid is formed out of two conjoined triangles](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mlx9t9awowvp5khy8pls.png)

It would have made little sense to split a trapezoid into two triangles to create a geometry like above. But what if you rotated every other circle of latitude by half a step - 11.25 degrees ( 0.5 \* 360degrees / 16 ) - so that, instead of straight lines running from the poles outward, the meridian lines would have to zigzag to connect the tips, thus forming neat triangles:

![A different approach to forming a sphere: from triangles rather than trapezoids, formed by meridians running from the poles outward in zigzags rather than in straight lines](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zhu0a13hoc7wy3su1pn7.png)

This seemed not just a step up from the previous paradigm. It was just perfect for the 3D Jack O' Lantern that I wanted to make for Kevin Powell's 3D CSS challenge: with sharp teeth and triangle-shaped cutout eyes. What's more, it let me lower the facet count, given how much was "carved away":

{% codepen https://codepen.io/MackFitz/pen/dyzjOQm %}

In reality, though, what CPU usage I saved there, I now had to transfer into calculating the bright orange facets of where the cutouts pierced the virtual flesh of the CSS pumpkin. In keeping with the Halloween spirit, this was a nightmare to figure out and coordinate, as was the faux texturing, done with gradients, which ran in straight lines like it would in my primary sphere, not in zigzags, like my facets did.

Also, my facets weren't actual vector vertices, they were just imitating those, just as the trapezoids were. Splitting the trapezoids in two would've made sense in a vector-based system. Here, I just doubled the facet count.

So can you blame me for going back to my original paradigm for my subsequent Hallooween's Jack O' Lantern?

{% codepen https://codepen.io/MackFitz/pen/BaPNyLw %}

This made the texturing way easier, and so I focused on that. Even so, I didn't quite achieve what I'd set out to do: I had to settle for linear gradients instead of conic gradients. Promised myself I'd keep trying and improve - next year!

And so I did!

![A different approach to forming a sphere than the basic geoid, where the polygon forming the vertical profile is titled by 11.22deg, thus resulting in a different, more efficient geometry](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6bzjmbesafh6woslubg8.png)

You're probably scratching your heads right now. Isn't this the same basic globe-like sphere, with meridians and circles of latitude? Yes - and no. The bases for both these spheres - the old one and the new one - look the same:

![The 16-gons forming the basic vertical profile of my spheres; almost identical, except one is titled by 11.25deg](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qfa87uxm57lrhp5flu1k.png)

Except they aren't the same. Notice that the right 16-gon is rotated by half a step - 11.25 degrees - similarly to what we did with every other circle of latitude in the second paradigm. So what you get both at the poles and the equator aren't sharp tips, it's flat surfaces. This results in the faces at the equator being perfect rectangles (left), not trapezoids (right):

![Two sphere paradigms side by side. Note how the right one is all trapezoids - and triangles near the poles - and the other  is all squares around the equator](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8sbrxzc4rypi2y3hvios.png)

Furthermore, the tips at the poles are no longer spiky, 16-gon-based pyramids. These triangles form a perfectly flat 16-gon. Which means we don't have to use 16 triangle-shaped containers to form a 16gon, we can just as well use a single, 16-gon-shaped div (one for each pole). This saves us a lot of computational power. We can even go as far as just rounding out our square container into a basic circle with border-radius: 50%

![In the current setup the secment closest to the poles is flat, so we don't need to make it out of 16 triangles, a 16gon or even a circle is just fine](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pcbfy4g4dzle17ablrb6.png)

How does that make it a better material for a Jack O' Lantern?

{% codepen https://codepen.io/MackFitz/pen/JjxEeKa %}

It doesn't, really. Again, the savings weren't as great as I'd have expected. The flat pole gets skipped altogether, as the Halloween pumpkin is usually gutted through the top of the head.

And so, the quest for the optimal approximation of the sphere continues - and Jack O' Lantern might not be the ideal test subject.