canvas 元素中的 JavaScript 球不跟随光标

标签 javascript canvas ecmascript-6

我正在尝试使用 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/

相关文章:

javascript - React 功能组件的功能或粗箭头?

javascript - 对象作为 React.memo 的 React 子项无效

javascript - 在没有jquery的情况下将javascript中的JSON输出为列表

node.js - node.js 上的 jsdom + canvas : toDataURL() error

c# - WPF: Canvas 吞噬 MouseDownEvent?

javascript - Html5 Canvas 游戏,创建比查看 Canvas 大得多的 map

javascript - 使用新的 ES6 Array.from() 方法

node.js - Sass 与 webpack 的相对导入

javascript - 单击按钮关闭窗口

javascript - 在 VS Code 中突出显示 "Cannot find name"/"any"