如何让Javascript Canvas返回x和y鼠标位置?

时间:2015-10-18 22:43:48

标签: javascript function event-listener mouse-position

我的目标是从鼠标的x和y位置获取实时更新输入。 y位置效果很好,但是当我加入x位置时,除了'NaN'之外我什么都得不到。

为什么这也不适合X职位?这不是如何通过函数传递对象?多个对象是问题吗?

这是我的代码:

canvas.addEventListener('mousemove',
    function(evt){
        var mousePos = calculateMousePosY(evt);
        paddle1Y = mousePos.y;
        //HERE IS WHERE I WANT X POSITION AS WELL
        paddle1X = mousePos.x; //Why doesn't this work?
    });
function calculateMousePos(evt){
    var rect = canvas.getBoundingClientRect();
    var root = document.documentElement;
    var mouseX = evt.clientX - rect.left - root.scrollleft;
    var mouseY = evt.clientY - rect.top - root.scrollTop;
    return{
        x:mouseX,
        y:mouseY        
    }

2 个答案:

答案 0 :(得分:1)

var mouseX = ... - root.scrollleft;更改为var mouseX = ... - root.scrollLeft;将' l'在' left'。

此外,您的功能称为calculateMousePos而不是calculateMousePosY。删除" Y"。

答案 1 :(得分:0)

您的代码有两处变化,

  • 你的函数调用拼写错误var mousePos = calculateMousePosY(evt);function calculateMousePos(evt){...}有一个额外的" Y"。
  • ,它是scrollLeft,有一个大写" L"。

请找到以下代码:[希望有帮助]

<强> HTML:

<canvas id="myCanvas" width="578" height="200"></canvas>

<强>使用Javascript:

&#13;
&#13;
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d'); 
canvas.addEventListener('mousemove',function(evt){
       var mousePos = calculateMousePos(evt);
       var values = 'Mouse position:' + mousePos.x + ',' + mousePos.y;
       display(canvas, values);
    });
function calculateMousePos(evt){
    var rect = canvas.getBoundingClientRect();
    var root = document.documentElement;
    var mouseX = evt.clientX - rect.left - root.scrollLeft;
    var mouseY = evt.clientY - rect.top - root.scrollTop;
    return{
        x:mouseX,
        y:mouseY        
    }
}
   
    
 function display(canvas, values) {
        var context = canvas.getContext('2d');
        context.clearRect(0, 0, canvas.width, canvas.height);
        context.font = '18pt Calibri';
        context.fillStyle = 'black';
        context.fillText(values, 10, 25);
}  
&#13;
<canvas id="myCanvas" width="578" height="200"></canvas>
&#13;
&#13;
&#13;