Html
Let's write the code in the file 1.html
<html>
<!-- heading -->
<head>
<meta charset="utf-8">
<title>Example</title>
</head>
<!-- page -->
<body>
<!-- HTML canvas -->
<canvas id="canvas1" width='400px' height='300px' style='border:1px solid gray;'></canvas>
<!-- JavaScript Functions -->
<script>
function MyDrawText(context, text, color, font, x, y)
{
context.font = font;
context.fillStyle = color;
context.fillText(text, x, y);
}
function MyCalculateMousePosition(canvas, event)
{
var rect = canvas.getBoundingClientRect();
return {
x: event.clientX - Math.trunc(rect.left),
y: event.clientY - Math.trunc(rect.top)
};
}
</script>
<!-- master code -->
<script>
<!-- context for drawing -->
var canvas = document.getElementById('canvas1');
var context = canvas.getContext('2d');
canvas.addEventListener('mousemove', function(evt)
{
<!-- clear everything on canvas -->
context.clearRect(0, 0, canvas.width, canvas.height);
<!-- get the position of the mouse -->
var mousePos = MyCalculateMousePosition(canvas, evt);
var message = 'Mouse position: ' + mousePos.x + ',' + mousePos.y;
MyDrawText(context, message, "black", "18pt Calibri", 0, 20);
}, false);
</script>
</body>
</html>