Ask coding questions

← Back to all posts
Q: How can I detect key presses in Javascript canvas ????
SudhanshuMishra (202)

here is how I am doing this

var screen = document.getElementById("screen2d");

var ctx = screen.getContext('2d');


ctx.fillStyle = "black";

ctx.fillRect(0,0,screen.width,screen.height)

ctx.fillStyle = "white";

x1 = 20;
y1 = 30;

var paddle1 = ctx.fillRect(x1 , y1 , 20 , 150)


x2 = screen.width - 40;
y2 = screen.height - 300;

var paddle2 = ctx.fillRect(x2 , y2 , 20 ,150)

window.addEventListener("keydown" , function (i){
	screen.key = false;
} )



window.addEventListener("keyup" , function (i){
	screen.key = false;
})


if(screen.key && screen.key == 87){
	y1 += 1;
}

But it seems like its not wrking and also this is'nt displaying any error Plz someone help me with this

here is the ping bro - @JULIODIAZ1

I am not sure if anyone will look at this post , so i am pinging the JS king - @coder100 plz help

Answered by Baconman321 (1058) [earned 5 cycles]
View Answer
Comments
hotnewtop
Baconman321 (1058)

We will look at your post, please don't ping. Besides, you don't need a king for this. Just bind the event listener to the canvas element itself and not the window. Example:

const canvas = document.querySelector("#canvas-id");
canvas.addEventListener("keyup", (evt) => {
   console.log(evt.key);
});

It's just like what you are doing but instead of binding to the window object bind it to the canvas element.

Coder100 (16872)

you should do keydown xd @Baconman321

Baconman321 (1058)

@Coder100 it depends on your needs. Keypress won't detect some keys (at least, to what I have experienced), but it will detect a keydown and keyup (hence the name "key press")

SudhanshuMishra (202)

this is very important to me