Skip to content Skip to sidebar Skip to footer

Html Canvas: How Do I Set Border Restrictions?

I have created a program that can move a rectangular block up, down, right, and left within a canvas using the w, a, s and d keys. I am having difficulty figuring out how to have t

Solution 1:

Here is pseudo-code for the basic boundary respecting movement functions:

// assuming this block object: var block={x:10,y:10,width:20,y:20};
function goLeft(){  if(block.x>0){block.x--;} }
function goUp(){    if(block.y>0){block.y--;} }
function goRight(){ if(block.x<(canvas.width-block.width)){block.x++;} }
function goDown(){  if(block.y<(canvas.height-block.height)){block.y++;} }

[Addition: Here's code based on the code you've added to your question]

Warning: untested code ... may need tweaking! :-)

// save the canvas width & height at the top of the appvar canvas=document.getElementById("canvas1");
var cw=canvas.width;
var ch=canvas.height;

functiononKeyPress(e){
    if (e.keyCode==87){
        positionY=Math.max(0,positionY-15);
    }
    if (e.keyCode==83){
        positionY=Math.min(cw-100,positionY+15);
    }
    if (e.keyCode==68){
        positionX=Math.min(ch-100,positionX+50);
    }
    if (e.keyCode==65){
        positionX=Math.max(0,positionX-50);
    }
    draw();
}

Post a Comment for "Html Canvas: How Do I Set Border Restrictions?"