-1

My goal is get live updating input from x and y position of my mouse. The y position works great, but when I went to add in the x position, I can't get anything but 'NaN'.

Why isn't this working for the X position as well? Is this not how to pass an object through a function? Is multiple objects the problem?

Here is my code:

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 Answers2

1

Change var mouseX = ... - root.scrollleft; to var mouseX = ... - root.scrollLeft; Capitalize the 'l' in 'left'.

Also your function is called calculateMousePos not calculateMousePosY. Remove the "Y".

pushkin
  • 9,575
  • 15
  • 51
  • 95
0

There are two changes in your code to be made,

  • your function call had a mismatch of spelling var mousePos = calculateMousePosY(evt);and function calculateMousePos(evt){...} there was an extra "Y".
  • and it is scrollLeft,with a capital "L".

Please find the code below:[Hope it helps]

HTML:

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

Javascript:

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);
}  
<canvas id="myCanvas" width="578" height="200"></canvas>
Pbk1303
  • 3,702
  • 2
  • 32
  • 47
  • That's embarrassing. I'm not new to coding and I swear I really tried. 2 hours.... Thanks for the catch, great lesson to emphasize 1 step at a time and I should have created another block to catch the 'l'-->'L' – user3158443 Oct 19 '15 at 01:42
  • @user3158443: Happy to help. Everyone has been in your place :-) so no problem, Please do accept the answer which suits you the most. Thank you. – Pbk1303 Oct 19 '15 at 01:45