Hosting Solutions
mobile_logo Table of Contents

Keyboard Control and Movement

In this exercise you can learn to apply custom keyboard controls to canvas applications and games. We can reference the keydown and keyup events of the document which returns event information to JavaScript about what keys the user is pressing on their keyboard. <!DOCTYPE html> <html> <head> <style> body{ background:#333; } #canvas_container{ width:1000px; margin: 20px auto; } #my_canvas{ background:#FFF; border:#999 1px solid; } </style> <script> var bg = new Image(); bg.src = "stars.jpg"; function initCanvas(){ var ctx = document.getElementById('my_canvas').getContext('2d'); var cW = ctx.canvas.width, cH = ctx.canvas.height; var dist = 3; function Background(){ this.x = 0, this.y = 0, this.w = bg.width, this.h = bg.height; this.render = function(){ ctx.drawImage(bg, this.x--, 0); if(this.x <= -499){ this.x = 0; } } } function Player(){ this.x = 0, this.y = 0, this.w = 50, this.h = 50; ctx.fillStyle = "orange"; this.render = function(){ ctx.fillRect(this.x, this.y, this.w, this.h); } } var background = new Background(); var player = new Player(); player.x = 100; player.y = 225; function animate(){ //; ctx.clearRect(0, 0, cW, cH); // Start drawing here background.render(); player.render(); // End drawing here //ctx.restore(); } var animateInterval = setInterval(animate, 30); document.addEventListener('keydown', function(event) { var key_press = String.fromCharCode(event.keyCode); //alert(event.keyCode+" | "+key_press); if(key_press == "W"){ player.y-=dist; } else if(key_press == "S"){ player.y+=dist; } else if(key_press == "A"){ player.x-=dist; } else if(key_press == "D"){ player.x+=dist; } }); } window.addEventListener('load', function(event) { initCanvas(); }); </script> </head> <body> <div id="canvas_container"><canvas id="my_canvas" width="1000" height="500"></canvas></div> </body> </html>

JavaScript Videos

Canvas Programming

2D Context Object and Rectangle MethodsFill and Stroke Styles Color Gradient PatternLine Styles for Lines and StrokesBuilding and Drawing PathsDrawing Images and VideosDrawing Text on CanvasRendering Shadows on CanvasCanvas Transformation EffectsPixel Manipulation on CanvasCompositing on the CanvasDynamic Centering and Alignment on the CanvasCanvas Animation and App InitializationObject Oriented Assets OOP on CanvasDetect Mouse Coordinates on CanvasAnimated Background Layers on Canvas TutorialKeyboard Control and MovementJSON Object Arrays and Loops on CanvasHit Detection Mouse Touch Over Object ArraysCollision Detection Hit Game EnemiesParticle Effect System Tutorial Snow Falling AnimationInteractive Canvas Imaging Applications JavaScript PHP TutorialCircular Progress Loader Canvas JavaScript Programming Tutorial