It’s already been years that I open-sourced Konfetti, a library to easily generate fun and realistic looking confetti in your app to celebrate special moments with your users.
What I always liked the most about Konfetti is how it has this 3D rotation. When talking with other developers I learned that people often assumed this 3D animation is very complex and perhaps done with OpenGL. When I explained them how it was done they were surprised how easy it was. In this post I show the 3 simple things needed to achieve this effect.
3D animation on a 2D Canvas
There are different ways of implementing a similar 3D effect on Android. You could go the more complex route and use OpenGL, however I needed to find an easier solution because I had no prior OpenGL experience and it sounded overkill for people to import an extensive OpenGL based library for something like this. The goal was to find a way that was both easy and lightweight.
Luckily there was a solution, and it only required a canvas and a shape to simultaneously behave in three ways: Rotate, Flip, and Move.
Let me break down the three different behaviours in this animation below:
Konfetti is built on top of a simplified particle system. All particles, in this case known as shapes, have gravity and a certain velocity. This will make a particle move and fall down. Let’s say we have a perfectly
symmetrical rectangular shape with some gravity applied to it, the animation will be quite boring. Let me show you:
Now, let’s rotate the shapes while it’s falling to see if the effect is somewhat better.
As you can see the animation is still quite boring and not close to realistic confetti as we know it. The last thing that we need to do is to scale the shapes whilst rotating. By scaling a shape from 100% to a width of 0 pixels and then back to a 100% will create the illusion as if it’s flipping over.
And that’s basically it. By simply combining three different animations you get this cool effect. To make it feel more realistic you can also play with the randomness of each animation. Each particle in Konfetti has its own speed for rotation, flipping and movement.
Show me some code
If you want to see this rotation and scaling actually implemented, click here.