Reputation: 97
I am trying to create a simple program in JavaScript ES6 that makes a ball follow my cursor. The ball moves, but it moves faster than my cursor. Here is the code:
index.html
is just a normal html document with a canvas element in it with an ID of "game_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
Update I removed the canvas argument from the getMousePos() function.
Upvotes: 0
Views: 110
Reputation: 97
I do not know why, so an explanation would be appreciated, but inserting a viewport tag like this one:
<meta name="viewport" content="width=device-width, initial-scale=1">
seems to have fixed the problem.
Upvotes: 1