Functional Reactive Programing with Elm: Part V - Animation
Now that we have understood Signals and Graphics in Elm, it is rather easy to create Animations.
Animation using Mouse Signals
Try this out by pasting this code in the online editor/runner. You should see that the image size is animated based on the x coordinate of the Mouse within the window.
Let us see if we can understand this code. The first thing is to create a function that displays an image (Feel free to replace this image with any image you like to animate and continue the exercises). This function animatedImage takes two parameters set the width and height of the the image.
Now in order to animate it we need to map this function over a Signal that contains your mouse x and y coordinates. But we know how to do that from our examples using Signals; just use Signal.map. And we are done!
Exercise
Animate an image where width and the height of the image depend on the number of mouse clicks.
Now we can look at a couple of more elaborate examples:
A Bouncing ball
A clock
These examples are triggered by special events fps : number -> Signal Time and every : Time -> Signal Time that are defined in the Time module. We discussed them briefly in the exercises in the section on Signals.
A bouncing ball
This is a very cool animation that requires you to figure out how to simulate an object falling in a gravitational field.
It is key to examine how the updates to position and velocity are done.
Try changing the bounceVelocity and the gravity parameters.
Exercises
Add a factor called elasticity and the update rule that
bounceVelocity = elasticity * bounceVelocity and modify the type alias Ball = { height : Float, velocity : Float, bounceVelocity}. This will simulate the effect of elasticity. The ball bounces should progressively decrease in height and finally come to a stop.
Many Bouncing Balls
Can we extend the Bouncing ball example to many bouncing Balls?
I ended up using the extremely useful library Signal.Extra.
But this means that you will have to run this program locally since try-elm does not support Signal.extra currently.
If you don’t what to get side tracked into installs at this time, you could just browse the code to understand the key ideas.
A clock
This is one of the examples from the elm site.
You can find other interesting examples there as well.
Animated batman
An here is a cool batman animation. Yan either hypnotize yourself or get dizzy watching this animation!
In this case creating the image that you wanted to animate was the most work. Unlike the bouncing ball where figuring out how to simulate gravity took more effort.