0
矩形不會離開畫布
所以我創建使用JavaScript。這部影片在畫布上的一個矩形: https://www.youtube.com/watch?v=8ZPlNOzLrdw如何讓使用Javascript
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);
}
}
}
然而,當我按下鍵周圍,當它移動矩形到達不停止的邊緣。如何創建一個函數等,使其保持在畫布中,並在到達邊緣時停下來?
感謝您的幫助!
_我的代碼看起來完全相同._ - **什麼**代碼?請[編輯]您的問題以提供上述代碼。 –
我已經添加了代碼,我的意思是它在YouTube視頻中。 –