Home » Design, HTML5, Javascript

Adding HTML5 Canvas Mouse Events using javascript

3 October 2012 No Comment
Share on Facebook

HTML5 canvas element can be interacted with mouse to get input from user in game or web application. This simple article explains how to add mouse interaction events in HTML5 Canvas element. Since canvas element responds to javascript, we are going to use javascript to add mouse events. Tutorial Difficulty:

  • Basic users

Lets us see how to add the following mouse events in html5 canvas

  • onmousedown
  • onmouseup
  • onmousemove

HTML5 Canvas Mouse Events using javascript

Some of the mouse events in HTML5

  • onclick
  • ondblclick
  • onmousedown
  • onmouseup
  • onmouseover
  • onmouseout
  • onmousemove

onmousedown event in HTML5 Canvas:

onmousedown event fires when the user press the mouse button. This event can be used for circumstances where you want to trigger an action while the mouse is pressed. Code to add Canvas Mouse Down Event:

canv.addEventListener('mousedown', function(e)
		console.log("Mouse Down");
 	}, true);

onmouseup event in HTML5 Canvas:

onmouseup event fires when the mouse button is released by user and is usually used to end whatever action the onmousedown event started. Code to add Canvas Mouse Up Event:

canv.addEventListener('mouseup', function(e)
		console.log("Mouse Up");
	}, true);

onmousemove event in HTML5 Canvas:

onmousemove event fires when the user moves mouse on the target area. Code to add Canvas Mouse Move Event:

canv.addEventListener('mousemove', function(e)
		console.log("Mouse Move");
	}, true);

Entire code for handling html5 mouse events:

<!doctype HTML>
<title>HTML5 Canvas Mouse Events</title>
<script type="text/javascript">
function init(canvas)
	var canv = document.getElementById("canv");
		canv.style.position = "absolute";
		canv.style.border = "1px solid";

	var textA = document.getElementById("textA");
		textA.style.height = "300px";
		textA.style.width = "300px";	

	canv.addEventListener('mousedown', function(e) {
		console.log("Mouse Down");
		textA.value += "Mouse Down \n";
		textA.scrollTop = textA.scrollHeight;
 	}, true);

	canv.addEventListener('mousemove', function(e) {
		console.log("Mouse Move");
		textA.value += "Mouse move \n";
		textA.scrollTop = textA.scrollHeight;
	}, true);

	canv.addEventListener('mouseup', function(e) {
		console.log("Mouse Up");
		textA.value += "Mouse Up \n";
		textA.scrollTop = textA.scrollHeight;
	}, true);
<body onLoad="init()">
<canvas id="canv" width="300px" height="300px">
<div style=" position:absolute; left:350px;">
	<textarea id="textA"></textarea>

Here, we are capturing the HTML5 Canvas Mouse Events in the text area and browser Console. Conclusion: In this articleswe have discussed about how to handle html5 canvas mouse events. Keywords to here:

  • html5 mouse events
  • canvas mouse events
  • html5 canvas events


We don't share your email anywhere, grab our rss via feedburner