Snake Game With Rust, JavaScript, and WebAssembly | Part 3

This is part of the course “Snake Game With Rust, JavaScript, and WebAssembly”.

GitHub Repository and Deployed Game

In this part, we will render all the objects of the game. Changes that we will introduce in this part reflected in this commit.

We are almost ready to render all objects of the game. The only field that we were unable to reach from JavaScript was the snake. Let’s fix this.

We will use js-sys dependency to return JavaScript Array of vectors. Let’s add it to the list of dependencies in Cargo.toml.

wasm-bindgen = "0.2"
js-sys = "0.3.32"

Now we can add a public method that will return an Array. It will clone the snake, and convert each vector to JavaScript value.

Before writing rendering logic, we want to prepare the HTML. To make content take the full height of the page, we make the height of html and body equal to 100%. In the body, we have a place for current and best scores and container for canvas, that we attach in JavaScript.


All the rendering will happen in the View class.


The constructor of the View class receives a callback so that the owner of an instance could make an extra rerender if needed. Later we will see how GameManager will handle this callback.


In the setUp() method, we take the width and height of the container to calculate the conversion rate between cells and pixels. Then we create two functions that will help us to project distances and positions from game to the view. Finally, we set up a canvas for rendering.

projecting vector from game to screen

The last method receives the positions of the food and snake and scores to render all game objects. First, it clears everything from the previous render. Then it creates a field that looks like a chess-board. After that, it renders food and snake. Finally, it shows the current and best scores.

To bind it all together, let’s go to the GameManager class.


In the constructor, we create an instance of View class. To make an extra rerender on resizing, we pass the bound resize method.

Now, we can open a web page, see how everything is rendered and try to resize the window.

resizing the window

In the next part, we will implement logic to place food in a random place that is free from the snake.

Reach the next level of focus and productivity with


Software engineer, creator of More at