HTML5 canvas how to give it a boundary?

2019-09-16 02:58发布

问题:

for a school assignment i am making a kite game..

i am a total javascript noob and i really need some help.

so i am at the point that i have an image moving by pressing the arrow buttons. the problem now is that my image can go outside of the canvas and i want it not to..

i really have nooooo idea how to do this i have tried multiple tutorials but it doesnt seem to work.

 window.onload = function() {

 var canvas = document.getElementById("game");
 window.addEventListener('keydown', keyDown, true);

 var context = canvas.getContext("2d");
 var kite = document.getElementById("kite");

 var kite = new Image ();
 kite.src = "kite.png";

 context.drawImage(kite, 250, 300, 300, 150);

 var x = 250;
 var y = 300;

 function keyDown(e){

//  up
    if (e.keyCode == 38) {
        clearCanvas();
        y = y - 3;
        context.drawImage(kite, x, y, 300, 150);    
    }

//  down
    if (e.keyCode == 40) {
        clearCanvas();
        y = y + 3;
        context.drawImage(kite, x, y, 300, 150);
    }

//  left
    if (e.keyCode == 37) {
        clearCanvas();
        x = x - 10;
        context.drawImage(kite, x, y, 300, 150);
    }

//  right
    if (e.keyCode == 39) {
        clearCanvas();
        x = x + 10;
        context.drawImage(kite, x, y, 300, 150);
    }

}

function clearCanvas() {
    canvas.width = canvas.width;
}



};

i would really really appreciate it if someone could help me with this :D

回答1:

You would need to do something along these lines for each keyStroke where you adjust the x or y variable. Notice the new if statement:

//  up
if (e.keyCode == 38) {
    clearCanvas();
    if (y - 3 > 0) {
        y = y - 3;
    }
    context.drawImage(kite, x, y, 300, 150);    
}

//  down
if (e.keyCode == 40) {
    clearCanvas();
    if (y + 3 + 150 < canvas.height) {
        y = y + 3;
    }
    context.drawImage(kite, x, y, 300, 150);
}

//  left
if (e.keyCode == 37) {
    clearCanvas();
    if (x - 10 > 0) {
        x = x - 10;
    }
    context.drawImage(kite, x, y, 300, 150);
}

//  right
if (e.keyCode == 39) {
    clearCanvas();
    if (x + 10 + 300 < canvas.width) {
        x = x + 10;
    }
    context.drawImage(kite, x, y, 300, 150);
}