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

94
Vistas
Making boundary for canvas

I am trying to create a boundary for my canvas, I am not sure where to begin to do that. I have already created the starting point made the character asset, that can move, however, the character moves outside the canvas, I want to make it when it hits the wall it does not move outside the boundary.

Here is the CSS code:

#canvas
{
  width: 500px;
  height: 200px;
  border: 1px solid black;
  margin: auto;
  margin-top: 200px;
}

#character
{
  width: 12px;
  height: 12px;
  background-color: blue;
  border-radius: 20px;
  position: relative;
  top:100px;
  left: 250px;
}

.animate
{
  animation:UpKey 300ms linear;
  animation:DownKey 300ms linear;
}

JavaScript code:

function place(id,x_pos, y_pos)
{
  var 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)
{
  var x = e.keyCode;

  var character = document.getElementById("character").getBoundingClientRect();

  var left = parseInt(character.left,10);
  var top = parseInt(character.top,10)

  switch (x) {
    case 37:
        place('character', left-10, top);
      break;
    case 39:
        place('character', left+10, top);
      break;
    case 38:
        place('character', left, top-10);
      break;
    case 40:
        place('character', left, top+10);
      break;
  }

 

  console.log(x);
}
update();

I am looking to do it in JavaScript

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Before setting the new position to the object (state), you need to calculate the value beforehand and check, if the value is out of bounce of your canvas.

This would be the minimal change needed to set the boundaries. You allow position changes only, when the requirement is met.

  switch (x) {
    case 37:
        if (left-10 >= 0)
        place('character', left-10, top);
      break;
    case 39:
        if (left+10 <= canvasWidth)
        place('character', left+10, top);
      break;
    case 38:
        if (top-10 >= 0)
        place('character', left, top-10);
      break;
    case 40:
        if (top+10 <= canvasHeight)
        place('character', left, top+10);
      break;
  }

There are a lot of improvements possible in your code:

  • cache the value for the character on global scope, instead on every key press
  • store the state inside a value store instead of reading it from the render object
  • Separate your update logic into a single update() function
  • Separate the rendering into a single render() function (render should be called after update)
  • use requestAnimationFrame instead of setInterval
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