handling keyboard event using JQuery

jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development

you can download Jquery from here

for keyboard event visit this link

Below is a working example in which you can move your image left/right or up/down using wasd Keys. hope you enjoy it

<!DOCTYPE HTML>
<html>
    <head>
		<script src="js/jquery-1.7.1.js"></script>
        <script>
	var canvas;
	var context;
	var destX = 10;
	var destY = 100;
	var imageLoaded = false;
	var imageObj = new Image();
	var x_move = 0;
	var y_move = 0;
	var speed = 2
        window.onload = function(){
		canvas = document.getElementById("myCanvas");
		context = canvas.getContext("2d");
		// onload handler
		imageObj.onload = function(){
		setInterval(render,17);
		};
		// loading request
		imageObj.src = "img/avatar.png";
		// 
		$(document).keydown(function(e){
		var code = (e.keyCode ? e.keyCode : e.which);
		switch(code){
		case 65: //this is left! (a)
		x_move--;
		break;
		case 68: //this is right (d)
		x_move++;
		break;
		case 87: //this is up! (w)
		y_move++;
		break;
		case 83: //this is down! (s)
		y_move--;
		break;
		}
		//	alert(code);
		});

		//$(document).keyup(function(e){
		//var code = (e.keyCode ? e.keyCode : e.which);
		//alert(code);
		//});

		function render()
		{
			destX = destX + x_move * speed;
			destY = destY + y_move * speed;
			canvas.width = canvas.width;
			context.drawImage(imageObj, destX, destY);
		}
		};
        </script>
    </head>
    <body>
	<canvas id="myCanvas" width="600" height="400"></canvas>
    </body>
</html>

 

About Jeetendra Chauhan

I am a s/w developer. love to code
This entry was posted in HTML5. Bookmark the permalink.

Leave a comment