所以我在画布上使用javascript创建了一个矩形,如下所示: https://www.youtube.com/watch?v=8ZPlNOzLrdw
window.onload = function()
{
var canvas = document.getElementById("c");
canvas.addEventListener('keydown', moveIt, true);
ctx = canvas.getContext("2d");
ctx.fillRect(100, 100, 30, 30);
var x = 100;
var y = 100;
function moveIt(e)
{
if (e.keyCode == 38)
{
ctx.clearRect(0, 0, canvas.width, canvas.height);
y = y - 10;
ctx.fillRect(x, y, 30, 30);
}
if (e.keyCode == 40)
{
ctx.clearRect(0, 0, canvas.width, canvas.height);
y = y + 10;
ctx.fillRect(x, y, 30, 30);
}
if (e.keyCode == 37)
{
ctx.clearRect(0, 0, canvas.width, canvas.height);
x = x - 10;
ctx.fillRect(x, y, 30, 30);
}
if (e.keyCode == 39)
{
ctx.clearRect(0, 0, canvas.width, canvas.height);
x = x + 10;
ctx.fillRect(x, y, 30, 30);
}
}
}
然而,当我按下按钮在到达边缘时移动矩形时,它不会停止。如何创建一个函数等以将其保留在画布中并在到达边缘时停止?
感谢您的帮助!
答案 0 :(得分:0)
在移动之前,您只需要额外的if语句来进行检查。在向下移动之前,您需要确保y > 0
,y < canvas.height - 30
(30为正方形的高度),然后向下移动,x
的宽度相同。以下代码适合您:
function moveIt(e) {
if (e.keyCode == 38){
if(y > 0){
ctx.clearRect(0, 0, canvas.width, canvas.height);
y = y - 10;
ctx.fillRect(x, y, 30, 30);
}
}
if (e.keyCode == 40){
if(y < canvas.height - 30){
ctx.clearRect(0, 0, canvas.width, canvas.height);
y = y + 10;
ctx.fillRect(x, y, 30, 30);
}
}
if (e.keyCode == 37){
if(x > 0){
ctx.clearRect(0, 0, canvas.width, canvas.height);
x = x - 10;
ctx.fillRect(x, y, 30, 30);
}
}
if (e.keyCode == 39){
if(x < canvas.width - 30){
ctx.clearRect(0, 0, canvas.width, canvas.height);
x = x + 10;
ctx.fillRect(x, y, 30, 30);
}
}
}