Functional Reactive Programing with Elm: Part III - Elm Graphics
Let us get started by drawing some simple shapes.
You can just enter this code in the online editor/runner.
Now let us see if we can understand how this code works. At the top of the code you are seeing a set of import statements, that allows the elm compiler to include all the packages containing the functions we want to use. In this case the packages are Color, Graphics.Element and Graphics.Collage.
Now let us look at the function main
what it does is to construct a graphics Element which then gets displayed. The graphics Element is constructed by calling the function collage
which takes as input two integers (which define the dimensions of the collage) and a list of Form objects that it then converts to graphics Elements. The signature of the collage function which makes all this explicit is as follows:
collage : Int -> Int -> List Form -> Element
We need to understand two more functions to get the full picture:
-
First we create a Shape using the function
square
which creates a square with the given edge length (side).square : Float -> Shape
-
Then we pass this Shape to the function
filled
which takes the Shape and a color and returns a Form which can be passed to collage.filled : Color -> Shape -> Form
That is all there is to it!
Exercises
-
Try changing colors and sizes on the square to see how this all works.
-
Using the documentation see if you can create a red circle. (Hint: Create a new function makeCircle similar to makeSquare.)
-
Try and make a blue square of side 40 and a circle of radius 60. (Hint: collage will accept a list of Shape Forms.)
You will find the complete documentation for the Graphics.Collage package at this link
More Shapes
Let us create a few more shapes using functions that are defined in Graphics-Collage. The shapes we will consider are:
- Triangle
- Rectangle
- NGon with n sides
- NGon with n vertices
Exercises
-
Write code that makes a blue pentagon.
-
Write code to make a red hexagon.
Shapes with Fills and Outlines
So far we looked at shapes which were filled with a chosen color. But we can also make figure with outlines as shown below:
Exercises
- Write code the makes a square with a
dashed
outline. (Hint you can use the functiondashed
instead of )
Transforming Shapes
Now that we have a set of shapes to work with we can look at functions that transform them.
Making a Star - using triangles and transformations
Once we understand transformations we can use them to create more complex shapes and figures.