This code is for drawing a snake to make the snake game. I am having trouble understanding the parameters of the drawSnake function and calling the function
//ctx is a reference to the id of the canvas
var ctx = document.getElementById('ctx').getContext('2d');
var WIDTH = 500;
var HEIGHT = 500;
var snakeList;
ctx.font = "20px Calibri";
var snakeBody = {
width:20,
height:20,
color:'green'
};
drawSnake = function(sb,i) {
ctx.save();
if (i == 0)
ctx.fillStyle = 'black';
else
ctx.fillStyle = snakeBody.color;
ctx.fillRect(sb.x,sb.y,snakeBody.width,snakeBody.height);
ctx.restore();
}
startGame = function() {
snakeList = [{x:220,y:200},
{x:210,y:200},
{x:200,y:200}];
snakeList.forEach(drawSnake);
}
startGame();
in drawSnake function,
- Where is
icoming from and what is it? - How is
sbsomehow taking values from snake List whensnakeListis not called in thedrawSnakefunction
in startGame function, where snakeList.forEach(drawSnake);
- How is drawSnake being called without passing in its parameters?
forEach. w3schools.com/jsref/jsref_forEach.asp.forEachiterates through the array, and for each object in the array, passes that object and the array index value as the two parameters to the function.