locked
Get Mouse Position using HTML5/JavaScript RRS feed

  • Question

  • Hello.

    I am clicking the canvas element and want to get mouse coordinates of the mouse. How can I do this?

    Thank you!


    Microsoft Student Partner

    Thursday, April 26, 2012 8:57 PM

Answers

  • Check this example out.

    <body>
        <div id="status">Position</div>
        <div>
            <canvas id="myCanvas" width="600" height="300" style="background-color: white;"></canvas>
        </div>
    </body>

    function writeMessage(message) {
            document.getElementById("status").innerText = message;
        }
    
        function getMousePos(evt) {      
            var canPos = WinJS.Utilities.getPosition(evt.currentTarget);
            var mouseX = evt.clientX - canPos.left;
            var mouseY = evt.clientY - canPos.top;
            return {
                x: mouseX,
                y: mouseY
            };
        }
    
        WinJS.Utilities.ready(function () {
            var canvas = document.getElementById('myCanvas');
            canvas.addEventListener('mousemove',
                function (evt) {
                    var mousePos = getMousePos(evt);
                    var message = "Mouse position: " + mousePos.x + "," + mousePos.y;
                    writeMessage(message);
                }, false);
        });

    Friday, April 27, 2012 12:55 PM

All replies

  • Check this example out.

    <body>
        <div id="status">Position</div>
        <div>
            <canvas id="myCanvas" width="600" height="300" style="background-color: white;"></canvas>
        </div>
    </body>

    function writeMessage(message) {
            document.getElementById("status").innerText = message;
        }
    
        function getMousePos(evt) {      
            var canPos = WinJS.Utilities.getPosition(evt.currentTarget);
            var mouseX = evt.clientX - canPos.left;
            var mouseY = evt.clientY - canPos.top;
            return {
                x: mouseX,
                y: mouseY
            };
        }
    
        WinJS.Utilities.ready(function () {
            var canvas = document.getElementById('myCanvas');
            canvas.addEventListener('mousemove',
                function (evt) {
                    var mousePos = getMousePos(evt);
                    var message = "Mouse position: " + mousePos.x + "," + mousePos.y;
                    writeMessage(message);
                }, false);
        });

    Friday, April 27, 2012 12:55 PM
  • Thank you very much! It works :)

    Microsoft Student Partner

    Friday, April 27, 2012 6:49 PM