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 mycanva
s
and width, height as "600" and "300".
In this code we have defined the two functions to call the functions
writeMessage(canvas, message)
(0,0, 600, 00
)
as the (x value, y value, width value and height as 600, 300)"20pt calibri "
defines the font size of the text 'blue';
-It defines the textcolor as bluecontext.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
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()output
Views: 13538 | Post Order: 47