Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading