Before you read any further, think about how you go about making this effect?
There are many ways to achieve it, but here, only CSS is used. The only thing that changes in page is the name of a single CSS class, the rest is done by the browser itself.
Cut with CSS
The web is for all intents and purposes square. With CSS clip-path
however, you can cut the squares into
different shapes. Here are some simple examples:
<div style="clip-path: circle(20px at 24px 25px); ... "></div>
<div style="clip-path: polygon(50% 0%, 100% 50%, 50% 100%, 0% 50%); ..."></div>
<div style="clip-path: polygon(50% 0%, 100% 50%, 50% 100%); ..."></div>
Of course, you can make these shapes with SVG, so why bother with clip-path
? Well, you can cut anything, including SVG
elements. A natural use case would be to cut images, e.g to make round profile pictures which are all the rage these
days.
The bonus is that clip-path
is a CSS property that is possible to animate with CSS transition. That is all
we need to make the morphing animation in the beginning of this post.
The HTML for the triangle is this:
<div id="example"
class="steg-1"
onclick="...">
<div class="trekant">PUSH ME</div>
</div>
The styling is as follows:
<style>
.trekant {
width: 100px;
height: 100px;
background: pink;
transition: all 2s ease;
margin-left: 50px;
font-size: 0.5rem;
text-align: center;
}
/* State for step 1 */
.steg-1 > .trekant {
clip-path: polygon(0% 0%, 100% 0, 50% 100%);
}
/* State for step 2 */
.steg-2 > .trekant {
clip-path: polygon(0% 50%, 50% 100%, 100% 50%);
}
</style>
For at transisjonen skal fungere så må du ha likt antall punkter i polygonene.
Click-handler er tatt rett ut fra 2000-tallet. Det eneste den gjør er å alternere mellom stegene ved å bytte ut klassen.
((e,obj) => {
if (obj.className==='steg-1') {
obj.className = 'steg-2'
} else {
obj.className = 'steg-1'
}})(event,this)
That's all there is to it. These are all the building blocks required to morph the shape of the tree to shape of the deer.
clip-path
is supported in all modern browsers.
Summary
With clip-path
you can transform any figure from one form to another. The only prerequisite is to declare how
each figure should look like, and then the browser fixes the transformation for you!
For the curious
To generate the CSS shapes above, I have cheated a little through a small ClojureScript program. You can read the source if you want. I drew the shapes in the example by hand.