JavaScript is a remarkable language, cobbled together in 10 days in 1995 and intended to be a forgiving language to enable simple pieces of interactivity to be incorporated into web pages, it now finds itself implemented in every graphical web-browser and the natural choice for writing client-side web-apps that run anywhere that will run a browser. Rather like a drunken tattoo of Baphomet acquired at a time when you’d no idea you would later wish to join the clergy, the issue now is how to deal with the consequences of this unforseeable unfortunate choice.
The Emscripten SDK containing the Emscripten compiler can be downloaded here. On Linux and MacOS some dependencies need to be installed prior to installing the compiler, details of these and instructions for their installation can be found here but after those are dealt with the installlation of Emscripten itself is quite straightforward; if you’re using the portable SDK it’s a case of unzipping it in a convenient place, changing into the ‘emsdk_portable’ directory and running the following commands which fetch the latest online tools from the web, installs them, and makes them active: ./emsdk update ./emsdk install latest ./emsdk activate latest Linux and MacOS X require a further step to set the system path to the active version of Emscripten: source ./emsdk_env.sh If all this has worked as it should, you should have the Emscripten compiler, emcc, at the file path ./emscripten/master/emcc in the emsdk_portable directory you downloaded.
Although you can do plenty of interesting things with just logic and text, to impress the man on the Clapham omnibus these days you generally need to do something graphical. To this end we’ll now write a program to load and show this fetching picture of an owl coughing up a pellet: Solving this problem can be broken down into two broad stages: firstly how do we refer to the image of an owl stored on a server’s file system when it will be viewed in a web-page visited from the client’s computer where JavaScript runs in a sandboxed environment?
We can now use SDL2 to load and display an image. The next step is to learn how to move this image, and then to use SDL’s functions to listen for user input in order to control the movement. Moving the image turns out to be one of those things that needs to be done a little differently to how it is normally done in native C/C++ programs. On those occassions you typically have a main event loop and inside that main loop you increment the position of the image a small amount on each iteration, something like this: /** * Initialise SDL and open window and renderer here */ bool carry_on = true; SDL_Surface *image = IMG_Load("assets/owl.png"); SDL_Texture *tex = SDL_CreateTextureFromSurface(renderer, image); int x = 0; /** * Have an infinite loop...