This post is the third part in a short series on programming web-enabled, functional-friendly applications in F# and has kindly been contributed with help from Alfonso Garcia-Caro. Thanks, Alfonso!
When it comes to client side development on the .NET stack, the approach that comes to mind for most people is Windows Forms or WPF, or perhaps Xamarin for a mobile application. Whilst these programming models have served the test of time, they're not the easiest development tools to use and there isn't a single cross platform approach to developing user interfaces. Thanks to advances with web browser technology, it's now possible to write applications which run across multiple devices within the web browser, whilst still achieving all of the functionality of a native application. For example, web browsers are now able to play back audio and video content, render 2D and 3D graphics through the GPU or even perform cryptographic tasks, all without the need for third-party plugins.
1: 2: 3:
1: 2: 3: 4: 5:
In an ideal world, we'd want to be able to develop browser-based applications in any language we choose to, much like we do when developing desktop and server applications. This is where the open-source project Fable comes in:
One of the APIs provided by all modern browsers is the canvas API which allows us to draw shapes and graphics at arbitrary points on the canvas. This makes it ideal for creating more rich experiences like games. Whilst we won't create a full game here, we will see how simple it is to draw shapes in the browser with Fable.
Assuming we already have a HTML page in place with a canvas on it, Fable allows us to easily write F# code which will retrieve a reference to the canvas and modify its size. The code then retrieves the canvas context which is what allows us to draw shapes on the canvas. Once we've got the canvas context, we're able to draw a number of rectangles with different colours.
1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17:
If you're interested in seeing more, there's a complete set of samples on available here.
By using the Fable compiler, we're able to run F# on devices and services we might not have previously been able to target. In the example below, we can see how we're able to write a short web service which can be run on a Node.JS server.