Add the Snake to the Board
Learn how to add the board and a snake to the canvas using JavaScript.
We'll cover the following...
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:
// Initializing the snake objectsnake = {length: 2, // the number of rectangles making up the snakecolor: "blue", // the color of the snakecells: [], // the positions of each of the rectanglesdirection: "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 ...