HTML5 Canvas Mouse Events
2 min readApr 26, 2021
How to handle mouse events on your Canvas?
Possible Mouse Events on Canvas
- mousedown / mouseup
- mouseover / mouseout
- mousemove
- click
- dbclick
Html
<html lang="en">
<head>
<title>Canvas Mouse Events</title>
<meta charset="UTF-8">
<link href="style.css" rel="stylesheet">
</head>
<body>
<canvas id="c" width="800" height="600">
This is a message for old browsers
</canvas>
<script src="script.js"></script>
</body>
</html>
Style.css
#c {
border: 1px solid;
display: block;
width: 800px;
height: 600px;
margin: 0 auto;
}
Script.js
Mouse up & Mouse down
window.onload = function () {
let canvas = document.getElementById('c');
let context = canvas.getContext("2d");
/**
* Mouse Events
* - mousedown / mouseup
* - mouseover / mouseout
* - mousemove
* - click
* - dbclick
*/
canvas.addEventListener('mousedown', function (event) {
console.log('mousedown');
console.log(event);
});
canvas.addEventListener('mousedown', function (event) {
console.log('mouseup');
console.log(event);
});
}
Mouse Over & Mouse Out
canvas.addEventListener('mousemove', function (event) {
console.log('mousemove');
console.log(event);
});
canvas.addEventListener('mouseout', function (event) {
console.log('mouseout');
console.log(event);
});
Click & Double Click
canvas.addEventListener('click', function (event) {
console.log('click');
console.log(event);
});
canvas.addEventListener('dblclick', function (event) {
console.log('dblclick');
console.log(event);
});
Mouse Over & Mouse Out
For info
Mouse Click = Mouse Down + Mouse Up
Result
You can check the code for this part here.
Thank you for your attention.
Thank you for your attention.
Do you need help with web or mobile development? Feel free to contact me here.
P.S. I really appreciate your like or share 🙏.