Fiddling with Go and SDL2 Part 1


Recently I fancied having a stab at getting GoLang to display 2D graphics as I was interested to see how difficult it was to do. As it turns out, it isn’t at all difficult at all as someone has created a Go binding for the SDL2 graphics library.

The SDL2 library lets us draw primitives such as lines, rectangles and circles to the screen. The library also lets us load image files (bmps or pngs etc) and display them on to the screen. It seems to me that loading image files would be the most fun to do.

Git Repo

The code for this can be found at the following repository

Simple Scrolling

To get started the first thing I am going do is draw an image on the screen and see if I can scroll it across the screen somewhat like you might see in a 2D game.

A quick disclaimer here, at the time of doing this I had / have no idea if the way I am about to explore is the prefered method to scroll graphics. It seems a bit lazy especially compared to the “olden days” where 8/16 bit machines had to work quite hard to perform horizontal scrolling.


I am going to draw a window on my computers desktop. And to keep this example simple, the window will be a fixed size. The figure below shows this, the large green rectangle is the computer’s desktop and the smaller window is the screen.

I will then create an image (in .png format) that is larger than this window. This image should be something like a city scape or similar rather than just a block of single colour or the scrolling won’t be obvious.

This image is going to move the image through the window to the left 1 pixel at a time to create the effect of scrolling.

The image below illustrates this, with the image position to the far left of the window. This is done by setting the X position of the image to 0

The window will be a fixed size say, 600px and the image will be larger say 1200px. This means the viewer will only ever see 600px of the image at a time.

Then create the effect of scrolling by subtracting 1 from the x value repeatedly. The image below shows this, as 1 is subtracted from the x position of the image, the image will gradually be dragged further to the left.

Getting Started

First thing that is needed is a folder to keep the code and assets in, in this case it is called golang-sdl2-scrolling.

mkdir golang-sdl2-scrolling

Also need a subfolder to keep our 2D images files in. We can call that that gfx.

mkdir -p golang-sdl2-scrolling/gfx

Create a blank go file with a main package and function, and save that as main.go

package main
func main() {


Next we add an import statement the log and runtime packages. Also create a little print statement to tell us a little about the go environment.

package main

import (

const info = `
Application %s starting.
The binary was built with GoLang: %s`
func main() {
	log.Printf(info, "Scrolling Demo", runtime.Version())

So far that doesn’t do much, just print the line about the environment. Now

Comments are closed.