HTML5 > Canvas

Canvas Mouse Events in HTML5

How to get the mouse coordinates using Canvas HTML5?


Mouse Coordinates 

To get the positions of the mouse coordinates placing on the screen, we need to use the getmousepos() which returns the positions of the mouse based on the screen with the canvas obtained from the getBoundingClientRect() method.

 <h1 style="color:green"><b><i>Please move your mouse on the page to get the co-ordinates</i></b></h1>
    <canvas id="myCanvas" width="600" height="300"></canvas>
    <script>
        function writeMessage(canvas, message) {
            var context = canvas.getContext('2d');
            context.clearRect(0, 0, 600, 300);
            context.font = '20pt Calibri';
            context.fillStyle = 'blue';
            context.fillText(message, 10, 25);
        }
        function getMousePos(canvas, evt) {
            var rect = canvas.getBoundingClientRect();
            return {
                x: evt.clientX - rect.left,
                y: evt.clientY - rect.top
            };
        }
        var canvas = document.getElementById('myCanvas');
        var context = canvas.getContext('2d');

        canvas.addEventListener('mousemove', function (evt) {
            var mousePos = getMousePos(canvas, evt);
            var message = 'Mouse Moving: ' + mousePos.x + ',' + mousePos.y;
            writeMessage(canvas, message);
        }, false);
    </script>

In the above code snippet we have defined the title as Mouse Events and canvas id as mycanvas and width, height as "600" and "300".

In this code we have defined the two functions to call the functions

  • In the script function we are having function as writeMessage(canvas, message) 
  • In this function we are defining the function write message to the  (canvas, message)
  • In the function we are declaring the canvas rectangle with (0,0, 600, 00) as the (x value, y value, width value and height as  600, 300)
  • Context.font="20pt calibri " defines the font size of the text 
  • context.fillStyle = 'blue'; -It defines the textcolor as blue
  • context.fillText(message, 10, 25); - It defines to fill the message with (x, y posistions )

function getMousepos(canvas, event) - It defines the function to the canvas and event 

  • We are having the mousepos as x and y with event clientx and event clienty which defines the positions of the (x, y) 
  • addeventlistener attaches the mousemo to the , function(evt)
  • varmousepos=getmousepos(canvas,evt) - It calls the function of getmousepos()
  • writeMessage(canvas, message);, false - It calls the canvas and message

output

 Views: 13112 | Post Order: 47



Write for us






Hosting Recommendations