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
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:
update()
functionrender()
function (render should be called after update)requestAnimationFrame
instead of setInterval