Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

164
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!