Charlie Kou
Charlie Kou

Reputation: 31

Javascript canvas context

I'm trying to bulid Snake game using HTML and Javascript, but I have this problem:

    context.fillStyle = 'red';
context.fillRect(
    apple.x * BLOCK_SIZE + 1,
    apple.y * BLOCK_SIZE + 1,
    BLOCK_SIZE - 1,
    BLOCK_SIZE - 1
);

context.fillStyle = 'lime';
for(var i = 0; i < snake.body.length; i++) {
    context.fillRect(
        snake.body[i].x * BLOCK_SIZE + 1,
        snake.body[i].y * BLOCK_SIZE + 1,
        BLOCK_SIZE - 1,
        BLOCK_SIZE - 1
    );
}

The red one is my apple and the lime one is my snake. When my snake touch the apple, it goes beneath it, so it'll looks like my game stops for a frame. Is there any way to make my snake always on top of my apple?

Upvotes: 0

Views: 90

Answers (1)

Helder Sepulveda
Helder Sepulveda

Reputation: 17664

If you are drawing in the order you show in your code, the snake goes on top of the apple...

The only way the snake goes beneath the apple is if you are drawing those elements in a different order, as far as I can see your code is good.

Here is a sample code snippet:

const BLOCK_SIZE = 12
var apple = {x:9, y:5}
var snake = {body: [{x:1, y:1}, {x:1, y:2}, {x:1, y:3}, {x:2, y:3}, {x:2, y:4}, {x:2, y:5}]}

var canvas = document.querySelector("canvas")
var context = canvas.getContext("2d")

function draw() {
  context.clearRect(0,0, canvas.width, canvas.height);

  context.fillStyle = 'red';
  context.fillRect( 
    apple.x * BLOCK_SIZE+1, 
    apple.y * BLOCK_SIZE+1, 
    BLOCK_SIZE-1, BLOCK_SIZE-1 );

  context.fillStyle = 'lime';
  for (var i = 0; i < snake.body.length; i++) {
    context.fillRect( 
      snake.body[i].x * BLOCK_SIZE+1, 
      snake.body[i].y * BLOCK_SIZE+1, 
      BLOCK_SIZE-1, BLOCK_SIZE-1 );
  }
}

function loop() {
  const last = snake.body.at(-1).x
  snake.body.push({x:last+1, y:5})
  draw()
}

draw()
setInterval(loop, 800);
<canvas id="canvas" width="240" height="140"></canvas>

Upvotes: 1

Related Questions