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

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

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