HTML5 canvas如何赋予它边界? [英] HTML5 canvas how to give it a boundary?
问题描述
我正在做一个学校作业,我正在制作风筝游戏。
for a school assignment i am making a kite game..
我是一个完全使用JavaScript的菜鸟,我真的需要一些帮助。
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;
}
};
如果有人可以帮助我,我真的很感激:D
i would really really appreciate it if someone could help me with this :D
推荐答案
您需要对每个按键执行以下操作,以调整 x
或 y
变量。请注意新的 if
语句:
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);
}
这篇关于HTML5 canvas如何赋予它边界?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!