【发布时间】:2017-09-24 23:54:07
【问题描述】:
所以我使用 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);
}
}
}
但是,当我按下键移动矩形到达边缘时它不会停止。如何创建一个函数等以将其保留在画布中并在到达边缘时停止?
感谢您的帮助!
【问题讨论】:
-
我的代码看起来一模一样。 - 什么代码?请edit您的问题提供上述代码。
-
我已经添加了代码,我的意思是它在 youtube 视频中。
标签: javascript html canvas rectangles