我正在尝试使用 JavaScript ES6 创建一个简单的程序,使球跟随我的光标。球移动了,但它移动的速度比我的光标快。这是代码:
index.html
只是一个普通的 html 文档,其中包含 ID 为“game_canvas”的 canvas 元素
game.js
// global vars
game_canvas = document.getElementById("game_canvas");
class Ball {
constructor() {
this.ctx = game_canvas.getContext("2d");
}
drawCircle(X, Y) {
this.ctx.beginPath();
this.ctx.arc(X, Y, 15, 0, 2 * Math.PI);
this.ctx.fillStyle = "red";
this.ctx.fill();
}
}
// MOUSE COORDS DETECTION
function getMousePos(event) {
return {
x: event.clientX,
y: event.clientY
};
}
// END COORDS DETECTION
let follower = new Ball(0, 0, game_canvas);
// START EVENT LOOP
game_canvas.addEventListener("mousemove", function(event) {
let mousePos = getMousePos(game_canvas, event);
follower.ctx.clearRect(0, 0, game_canvas.width, game_canvas.height);
follower.drawCircle(mousePos.x, mousePos.y);
}, false)
// END EVENT LOOP
更新我从 getMousePos() 函数中删除了 canvas 参数。
最佳答案
我不知道为什么,因此我们将不胜感激,但插入一个像这样的视口(viewport)标签:
<meta name="viewport" content="width=device-width, initial-scale=1">
似乎已经解决了问题。
关于canvas 元素中的 JavaScript 球不跟随光标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38800271/