我试图让一个球在画布区域内跟随鼠标移动。但是当鼠标进入画布区域时(即在边缘),球只会获得第一个位置。
为什么球在画布内移动时不跟随鼠标呢?请帮忙解决问题。
window.onload = startup;
var ballX = 400;
var ballY = 400;
var mouseX = 0;
var mouseY = 0;
function startup() {
document.getElementById("drawingArea").onmouseover = mouseMove;
setInterval("moveBall()", 100);
}
function mouseMove(evt) {
mouseX = evt.clientX;
mouseY = evt.clientY;
}
function moveBall() {
if (ballX > mouseX) {
ballX -= 5;
} else {
ballX += 5;
}
if (ballY > mouseY) {
ballY -= 5;
} else {
ballY += 5;
}
var canvas = document.getElementById("drawingArea");
var ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
ctx.arc(ballX, ballY, 40, 0, 2* Math.PI);
ctx.fillStyle = "green";
ctx.fill();
ctx.lineWidth = 5;
ctx.strokeStyle = "red";
ctx.stroke();
}
#drawingArea {
border-style: solid;
position: absolute;
top: 0;
left: 0;
}
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Move Ball</title>
</head>
<body>
<canvas id="drawingArea" width="800" height="800" />
</body>
</html>