var canvas, ctx, mousePos, mouseButton;
window.onload = function init() {
canvas = document.getElementById('myCanvas');
ctx = canvas.getContext('2d');
canvas.addEventListener('mousemove', function (evt) {
mousePos = getMousePos(canvas, evt);
var message = 'Mouse position: ' + mousePos.x + ',' + mousePos.y;
writeMessage(canvas, message);
}, false);
canvas.addEventListener('mousedown', function (evt) {
mouseButton = evt.button;
var message = "Mouse button " + evt.button + " down at position: " + mousePos.x + ',' + mousePos.y;
writeMessage(canvas, message);
}, false);
canvas.addEventListener('mouseup', function (evt) {
var message = "Mouse up at position: " + mousePos.x + ',' + mousePos.y;
writeMessage(canvas, message);
}, false);
};
function writeMessage(canvas, message) {
ctx.save();
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.font = '12pt Calibri';
ctx.fillStyle = 'black';
ctx.fillText(message, 10, 25);
ctx.restore();
}
function getMousePos(canvas, evt) {
// necessary to take into account CSS boudaries
var rect = canvas.getBoundingClientRect();
return {
x: evt.clientX - rect.left,
y: evt.clientY - rect.top
};
}
JS.Interact.MouseonCanvas.Ex3
-----------------------------
A [Pen](https://codepen.io/Onlyforbopi/pen/wEbGXK) by [Pan Doul](https://codepen.io/Onlyforbopi) on [CodePen](https://codepen.io).
[License](https://codepen.io/Onlyforbopi/pen/wEbGXK/license).
<!DOCTYPE HTML>
<html lang="en">
<head>
<!----
A good example that shows how to display the mouse position, and the mouse button that has been pressed or released
This example uses the previous function for computing the mouse position correctly. It listens to mousemove, mousedown and mouseup events, and shows how to get the mouse button number using the evt.button property.
-->
<title>Wrong way to get the mouse
position in a canvas</title>
<meta charset="utf-8">
<style>
body {
margin: 20px;
padding: 0px;
}
</style>
</head>
<body>
<p> Move the mouse cursor and click anywhere!</p>
<canvas id="myCanvas" width="300" height="200"></canvas>
</body>
</html>