Animating With Go

๐Ÿ•“ Dec 7, 2019 ยท โ˜•7 min read
๐Ÿท๏ธ
  • #animating
  • #go
  • circle

    The Abstract

    We've probably all tried it, or at least thought about it. Maybe?

    Anyhow, as the title suggests, we'll be animating with golang - and not just any animation, a sine-curve animation! Exciting? I know!

    As animating in any non-visual scripting-language can be rather tedious. Fortunately, some people have done most of the “tough” work for os, in most cases. Even in this coincidence, we can say, they've done most work for os. Which might be a good thing, if you're just coming into system-languages.

    The Beginning

    For now, let's make a new module - why a module? Well, because that's easier to manage, if you ask me.

    So, go ahead and run the magnificent go module command.

    1
    
    go mod init siney

    This will do the hard work and add a single file. Nice ‘eh?

    Jokes aside, let's move on!

    First of all. Let's start with the usual, boring stuff, that just has to be done. Create a new file, let's name it main.go fill it with

    1
    2
    3
    4
    5
    
    package main
    
    func main() {
    
    }

    Pretty easy? And tedious? Ye. Okay, now for more exciting stuff.

    Let's add a couple of variables, that'll help out in the future.

    1
    2
    3
    4
    5
    6
    7
    8
    
    package main
    
    const (
    	radius = 5
    	width  = 298
    	height = 150
    )
    ...

    You can set the with, height and radius to whatever you seem fit, I'll be using these values as they work well for a wider image.

    The Circle

    Our program doesn't do anything yet if you try to run it. So let's add a circle!

    This is the more fun part. Let's get going!

    First, let's make some imports

    1
    2
    3
    4
    
    package main
    
    import "github.com/fogleman/gg"
    ...

    Remember to save your program at every now and then.

    Now that that's been added. Let's go further adding more lines.

    I'll explain each one at a time. They should all be added one after another. All should be added within the main-fn.

    1
    
    dc := gg.NewContext(width, height)

    This will make use of our newly imported library github.com/fogleman/gg. It's a beauty if you're making static images with go! As you can see, we're using the width and height we created earlier, this will make a new image context of dimensions WxH.

    1
    
    dc.Translate(width/2, height/2)

    This will help us out in the future, it's simply moving our drawing pen to the center of our context.

    1
    
    dc.SetRGB(0, 0, 0)

    This will set our colour to black. Will also be used later.

    1
    
    dc.Clear()

    This is just an easy way to fill the image with our previously selected colour.

    1
    
    dc.SetRGB(1, 1, 1)

    Let's change the colour to white to see what we're drawing next.

    1
    
    dc.DrawCircle(0, 0 radius)

    This will make an invisible circle in the center of our image-context.

    1
    
    dc.Fill()

    Now we're actually filling the circle with our white colour.

    1
    
    dc.SavePNG("out.png")

    This will save the resulting image as out.png.

    circle

    By now you'd have a program looking quite like this.

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    
    package main
    
    import "github.com/fogleman/gg"
    
    const (
    	radius = 5
    	width  = 298
    	height = 150
    )
    
    func main() {
    	dc := gg.NewContext(width, height)
    	dc.Translate(width/2, height/2)
    
    	dc.SetRGB(0, 0, 0)
    	dc.Clear()
    
    	dc.SetRGB(1, 1, 1)
    	dc.DrawCircle(0, 0, radius)
    	dc.Fill()
    
    	dc.SavePNG("out.png")
    }

    Phew! Quite a mouthful, ‘eh? Worry not, though! This was the easy part…

    The PI

    How about we make a few more images? Like, say, a sine movement for the circle.

    Let's first of all put everything of our main-fn into a for-loop. Like so:

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    
    package main
    
    import "github.com/fogleman/gg"
    
    const (
    	radius = 5
    	width  = 298
    	height = 150
    )
    
    func main() {
    	for i := 0; i < 100; i++ {
    		dc := gg.NewContext(width, height)
    		dc.Translate(width/2, height/2)
    
    		dc.SetRGB(0, 0, 0)
    		dc.Clear()
    
    		dc.SetRGB(1, 1, 1)
    		dc.DrawCircle(0, 0, radius)
    		dc.Fill()
    
    		dc.SavePNG("out.png")
    	}
    }

    Already more complex. Now for even more complexity!

    Let's add another import, namely the fmt.

    Next, move the first two lines of of the loop out of the loop, like this.

    1
    2
    3
    4
    5
    6
    
    func main() {
    	dc := gg.NewContext(width, height)
    	dc.Translate(width/2, height/2)
    
    	for i := 0; i < 100; i++ {
    		...

    Add a math.Sin to the middle of our code, and change the y of our circle to sine.

    1
    2
    3
    4
    5
    6
    
    ...
    sine := math.Sin(x) * (height / 2)
    dc.SetRGB(1, 1, 1)
    dc.DrawCircle(0, sine, radius)
    dc.Fill()
    ...

    Now you might ask yourself:

    Where does that x come from?

    I have one answer. We haven't made it yet! So let's do that exact thing.

    Above the loop:

    1
    
    x := 0.0

    Along with:

    1
    
    increase := math.Pi * 8 / 100

    This says how much the x variable should increase every iteration of the loop.

    Let's add that logic below the save function.

    1
    
    x += increase

    Now for the use of the fmt-package we imported a little while ago.

    Change the SavePNG-line to:

    1
    
    dc.SavePNG(fmt.Sprintf("out-%d.png", i))

    This will save a lot of images, a hundred to be exact. You can run the program if you want, but I wouldn't recommend it.

    The Animation

    So, I promised you an animation, and we're not going to make use of ffmpeg or the gif package of go for this.

    So, let's import yet another package: "github.com/kettek/apng".

    Now for using it!

    Add these couple of lines above the for-loop:

    1
    2
    3
    
    anim := apng.APNG{
    	Frames: make([]apng.Frame, 100),
    }

    This will tell apng that we're going to be making an animation of 100 frames.

    If you don't know about apng, it's a, rather unused, format for creating animated png's. More on wikipedia.

    Now let's add the animation making. In our loop, below the Fill()-fn, add:

    1
    2
    3
    4
    
    buf := new(bytes.Buffer)
    png.Encode(buf, dc.Image())
    im, _ := png.Decode(buf)
    anim.Frames[i].Image = im

    This is a work around for not saving the image context upon it-self before it's actually saved.

    Let me explain. First we create a new buffer. We encode the image we get from our context and decode it again to another image context. This one we same as a frame in our animation.

    Remember to remove the dc.SavePNG("out.png")!

    Next, let's encode and save our newly created animation.

    Simply add these three lines:

    1
    2
    3
    
    out, _ := os.Create("out.png")
    defer out.Close()
    apng.Encode(out, anim)

    Those will create a new file on our OS, and save the animation in out.png.

    Easy, peasy!

    You are done!

    The Surprise

    Now, I couldn't let you off this easy, as I have another card up my sleeve!

    You've seen the image above. That's missing something, I mean, if you look at the first image of this post. It's missing a go-logo!

    Let's create that!

    First, make sure you've got an font at hand. I recommend Comfortaa Bold - it's free to use.

    1
    2
    3
    
    if err := dc.LoadFontFace("./font/Comfortaa-Bold.ttf", 126); err != nil {
        panic(err)
    }

    Next, we need some meaurements:

    1
    2
    
    gWidth, _ := dc.MeasureString("G")
    linesBegin := -gWidth + 30

    A couple of line-options.

    1
    2
    
    dc.SetLineCapRound()
    dc.SetLineWidth(radius * 2)

    And last but not least, add the highlighted lines:

     1
     2
     3
     4
     5
     6
     7
     8
     9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    
    package main
    
    import (
    	"bytes"
    	"image/png"
    	"math"
    	"os"
    
    	"github.com/fogleman/gg"
    	"github.com/kettek/apng"
    )
    
    const (
    	radius = 5
    	width  = 298
    	height = 150
    )
    
    func main() {
    	anim := apng.APNG{
    		Frames: make([]apng.Frame, 100),
    	}
    
    	dc := gg.NewContext(width, height)
    	if err := dc.LoadFontFace("./font/Comfortaa-Bold.ttf", 126); err != nil {
    		panic(err)
    	}
    
    	gWidth, _ := dc.MeasureString("G")
    	linesBegin := -gWidth + 30
    
    	dc.SetLineCapRound()
    	dc.SetLineWidth(radius * 2)
    	dc.Translate(width/2, height/2)
    
    	increase := math.Pi * 8 / 100
    	x := 0.0
    	for i := 0; i < 100; i++ {
    		dc.SetRGB(0, 0, 0)
    		dc.Clear()
    
    		dc.SetRGB(0.1, 0.1, 0.1)
    		dc.DrawStringAnchored("G", -15, 0, 0.5, 0.5)
    		dc.DrawStringAnchored("o", gWidth-43, 0, 0.5, 0.5)
    
    		dc.DrawLine(linesBegin, -radius*3, linesBegin-35, -radius*3)
    		dc.DrawLine(linesBegin, 0, linesBegin-50, 0)
    		dc.DrawLine(linesBegin, radius*3, linesBegin-20, radius*3)
    		dc.Stroke()
    
    		sine := math.Sin(x) * (height / 2)
    		dc.SetRGB(1, 1, 1)
    		dc.DrawCircle(0, sine, radius)
    		dc.Fill()
    
    		buf := new(bytes.Buffer)
    		png.Encode(buf, dc.Image())
    		im, _ := png.Decode(buf)
    		anim.Frames[i].Image = im
    		x += increase
    	}
    
    	out, _ := os.Create("out.png")
    	defer out.Close()
    	apng.Encode(out, anim)
    }

    You now have the exact image I'm using at the top of this post.

    PS. If you want to see what else could be made using this drawing process. Please checkout Trees From Space.

    - Thanks,

    Mads Cordes


    Mads Cordes
    WRITTEN BY
    Mads Cordes
    Dev of Sorts