Add the Snake to the Board

Learn how to add the board and a snake to the canvas using JavaScript.

Implement: Add the snake to the board

First, let's create the board and the snake. To do this, we will follow the steps below:

  • Create a canvas in HTML and set a background image for the snake game.

  • Create a snake object. A snake will be drawn as continuous rectangles. Each rectangle will denote one block of the snake. We will set the initial values to create a snake on the board (background image). We will set the initial length, the color, the initial direction in which the snake moves, and all the positions of the continuous rectangles denoting the snake. We will use arrays and objects to perform this operation. The snake object is shown below:

Press + to interact
// Initializing the snake object
snake = {
length: 2, // the number of rectangles making up the snake
color: "blue", // the color of the snake
cells: [], // the positions of each of the rectangles
direction: "right" // the direction in which the rectangle moves
}
  • We will also add two methods inside the snake object that will create (initialize) a snake and then draw the snake on the HTML canvas. The logic behind the two methods is discussed below:

    • createSnake(): This method will generate the position ...

Access this course and 1400+ top-rated courses and projects.