这是一个移动所有方向和边界检查的示例:
HTML:
<canvas id="canvas"></canvas><br>
<button type="button" onclick="moveRect(0, -10);">move up</button><br>
<button type="button" onclick="moveRect(-10, 0);">move left</button>
<button type="button" onclick="moveRect(+10, 0);">move right</button><br>
<button type="button" onclick="moveRect(0, +10);">move down</button>
JS:
var c = null, ctx = null, x = 0, y = 0;
var width = 150, height = 75;
function moveRect(x2, y2) {
ctx.clearRect(x, y, width, height);
x += x2;
if (x < 0) x = 0;
else if (x > c.width - width) x = c.width - width;
y += y2;
if (y < 0) y = 0;
else if (y > c.height - height) y = c.height - height;
ctx.fillRect(x, y, width, height);
}
window.onload = function() {
c = document.getElementById("canvas");
ctx = c.getContext("2d");
x = 0;
moveRect(0, 0);
}
CSS:
#canvas {
width: 200;
height: 300px;
border: 1px solid red;
}
另请参阅此示例。