Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

163
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda