United Kingdom: +44 (0)208 088 8978

Drawing vector shapes with SharpVG

SharpVG is a library that makes it easy to generate SVG files in F#.

We're hiring Software Developers

Click here to find out more

SharpVG is a library that makes it easy to generate SVG files in F#. SVG is a vector graphics format, meaning that rather than as a grid of pixels, the shapes are defined mathematically. Think trigonometry, but without a deep dive into celestial mechanics.

To use SharpVG you don't need deep understanding of the SVG format specification. You also won't need any external libraries other than SharpVG itself.

Create a new F# project and add the SharpVG package to it.

dotnet new console -lang "F#"
dotnet add package SharpVG

Then, open the project in your editor of choice.

As a preamble, we will put in the following code snippet that opens the SharpVG namespace and defines a simple file-saving function.

open SharpVG

let saveFile (filename:string) (svgContents:string) =
    System.IO.File.WriteAllText($"{__SOURCE_DIRECTORY__}/{filename}.html", svgContents)

Add the following snippet right under.

module Square =
    let position = Point.ofInts (10, 10)
    let area = Area.ofInts (50, 50)
    let styleSquare = Style.create (Color.ofName Colors.Cyan) (Color.ofName Colors.Blue) (Length.ofInt 3) 1.0 1.0

    Rect.create position area
        |> Element.createWithStyle styleSquare
        |> Svg.ofElement
        |> Svg.toHtml "Square"
        |> saveFile "Example1"

At this point you're ready to do a dotnet watch and find the Example1.html in the solution folder. Open it in your browser. You can edit the properties of the shape on-the-fly in your code editor and each time you save, the HTML file will be overwritten.
You'll still have to refresh it manually (F5) in the browser.

The next snippet will add another shape - a circle - and save it to its own file.

module Circle =
    let center = Point.ofInts (60, 60)
    let radius = Length.ofInt 50
    let styleCircle = Style.create (Color.ofName Colors.Violet) (Color.ofName Colors.Indigo) (Length.ofInt 3) 1.0 1.0

    Circle.create center radius
        |> Element.createWithStyle styleCircle
        |> Svg.ofElement
        |> Svg.toHtml "Circle"
        |> saveFile "Example2"

These are very basic examples, but hopefully you can see how those of us who find trigonometry fun could use this library to design their own icons/buttons/logos and produce files that will not get pixelated or blurry no matter how deep one might zoom in on them!