Part 3: User Input from Key listener in Canvas
We need to set up a canvas
- <html>
- <body>
- <canvas style="background-color:pink;" width="800" height="400" id="myCanvas"></canvas>
- <script>
- canvas = document.getElementById("myCanvas");
- ctx = canvas.getContext("2d");
- </script>
- </body>
- </html>
We will now need to get a background and a Sprite
- var background = new Image();
- background.src = "https://mrhorvathcompclasses.in/Canvas/CMS.jpeg";
- var char = new Image();
- char.src = "https://mrhorvathcompclasses.in/Canvas/char.png"
We will now need build variables and a Key Handler for movement
- var CharX=300;
- var CharY=300;
- function keyDownHandler(event){
- if (event.keyCode == 37) {
CharX -= 10;}
- else if (event.keyCode == 65) {
CharY -= 10;}
- else if (event.keyCode == 39) {
CharX += 10;}
- else if (event.keyCode == 90) {
CharY += 10;}
- }
- document.addEventListener("keydown", keyDownHandler);
We will now need build gameloop & draw
- function draw(){
- ctx.drawImage(background,0,0,canvas.width,canvas.height);
- ctx.drawImage(char, CharX, CharY, 200, 100);
- }
- function gameLoop(){draw();}
- var desiredFrameRate = 30;
- var delay = 1000/desiredFrameRate;
- setInterval(gameLoop,delay);
Hit ctrl-S to save and you are good to go.
use → to go right use ← to go left and a key to go ↑ and z key to ↓