“WebAssembly: A Game-Changer in Web Development”

In this article, we want to share our experience creating a Snake game for the browser with WebAssembly and Rust.

You can find a live demo of our game here and the source code here.

What is WebAssembly?

WebAssembly is a platform-independent format for executable programs and is intended as a compilation target for programming languages. WebAssembly was designed to run in the browser and complement JavaScript in two ways:

enabling near-native performance for web apps like games, image and video editing, image recognition, and many others

enabling the execution of existing or new code written in languages other than JavaScript in the browser

WebAssembly (WASM) is also increasingly relevant for server-side computing, and Solomon Hykes, a co-founder of Docker, even wrote:

If WASM+WASI existed in 2008, we wouldn’t have needed to create Docker. […] Webassembly on the server is the future of computing.

In this article, we focus on the use case of creating a browser game.

Why Rust?

WebAssembly had an initial focus on C/C++, but now many programming languages can compile to WebAssembly.

As computationally intensive tasks are a common use case for WebAssembly, using it with a low-level programming language is a natural choice. What makes Rust specifically attractive is the balance between emphasis on performance and avoidance of pitfalls typically associated with low-level languages like C/C++.

According to the report, The State of WebAssembly 2022 Rust has become the most frequently used as well as most desired language for WebAssembly development, making it even more attractive as the ecosystem grows with the popularity.

Tools

We used the recommended Rust crates wasm-pack and wasm-bindgen for compiling our Rust code to WebAssembly and facilitating interoperability with JavaScript. These libraries build the WebAssembly module as well as corresponding JavaScript wrappers that abstract low-level details of the interactions between the JavaScript and Rust code. You can find a great getting started guide here.

The crate web-sys provided us with the wasm-bindgen based imports for the browser APIs. It comes with an extensive list of examples.