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

97
Visualizações
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 Respostas
Responde à pergunta

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 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