Today I found another way to draw the Sierpinski triangle using pure CSS. There are no recursive divs corresponding to the fractal structure, so it's simpler and performs better.
The method is to use multiple background gradients to draw triangles that are controlled by background-size
.
Here is how
Actually, the whole code is pretty simple, but I'll try to explain it step by step.
Step 1
Let's add a linear-gradient
tilted with a degree to make it a triangle.
Step 2
Add another one with background-size
of 50% 50%
.
The previous background has a higher z-index value than the latter one when there are multiple backgrounds. And that's what we wanted: using smaller triangles to fill the holes.
Step 3
Then add enough levels of gradients. The background-size
is always half the size of the previous one.
Step 4
Swap background and gradients (triangles) colors.
Final step
Remove the top left part with mask
and adjust angle with transform
. See also the live example on CodePen.
How deep it can go
Chrome can render as many triangles as possible but Safari and Firefox don't work well as the triangle is getting smaller.
Hmmm
CSS is kind of different from any other tools. Sometimes you really need to think in CSS in order to develop an elegant solution.
The technique described in this article can be used to generate many interesting patterns too, together with radial-gradient
or conic-gradient
.
That would be another journey.
from Hacker News https://ift.tt/2SsMGFv
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.