Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

167
Visualizações
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?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

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>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda