✨ If you want to skip the reading and jump straight to the code, you will find it here. Also, I have deployed a live demo here.✨
Recently I have decided to refurbish something old, that I did 4 years ago for a project of mine. Here is how it looked like:
The "tube" component is easy. It's just a background image I am using to create an illusion that the balls are flying inside a sphere-like glass object. The interesting part is the code to create the animations and detect the collisions between the balls and the walls. But let's go step by step.
We said the "tube" is a background image I am adding via simple CSS background property. Let's see the balls themselves. For them I had two choices - try to draw circles in canvas and make them look like balls or use simple images. I choice the later option as I wanted to have more realistic view of the balls. So, with the help of a graphic processing program, a friend of mine created for me 75 images, one for each ball.
Having all the assets we need, we are now ready to go deeper and implement some physics with Matter.js.
Before going to the animation itself, we need to mention few Matter.js specific things. When creating animations with this library, one needs to define as minimum:
In our example we use further: