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

154
Vistas
How to make a Canvas boundary

I am trying to make a canvas boundary for my mini-game. I have already created the canvas with a character that can move with the arrows. I used a switch statement to do this, the next step is to create a boundary and I am not sure how to go about that? This is how the Javascript Code looks at the moment:

function place(id,x_pos, y_pos)
{
  let element = document.getElementById(id);
  element.style.position = "absolute";
  element.style.left = x_pos + 'px';
  element.style.top = y_pos + 'px';


}

setInterval(update,1);

function update()
{
  document.addEventListener('keydown', keyPress);
}

function keyPress(e)
{
  let x = e.keyCode;

  let character = document.getElementById("character").getBoundingClientRect();
  let canvasWidth = document.getElementById("canvas").getBoundingClientRect();
  let left = parseInt(character.left,10);
  let top = parseInt(character.top,10)

  switch (x) {

      //left
    case 37:
        place('character', left-15, top);
      break;
      //right
    case 39:
        place('character', left+15, top);
      break;
      //up
    case 38:
        place('character', left, top-15);
      break;
      //down
    case 40:
        place('character', left, top+15);
      break;
  }
  console.log(x)
  return x
}
update()
over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

I'm assuming the boundary you're talking about is a boundary for your character to move? If so...

You'll want to check in the keyPress method before moving your character.

Something like this:

First, I'd consider renaming canvasWidth to something like canvasBound, and similarly for your character bounds variable.

if (!(characterBound.left - 15 < canvasBound.left)) {
   ...move character left...
} 
... else do nothing (don't have to actually include this)

repeat similarly for moving up, down, right, etc. You'll have to play with the values to get it right for your sprite.

over 4 years ago · Santiago Trujillo 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