Having trouble with the Keydown event - the image isn't moving as expected

Something seems off with my code. I have an image displayed on a canvas, but when I press the specified key, nothing happens. Can you help me figure out where I went wrong?

  let img = document.getElementById("ship");
let player = {
  x: 375,
  y: 550,
  w: 50,
  h: 50,
};
requestAnimationFrame(draw);

function draw() {
  //Logic
  ctx.drawImage(img, player.x, player.y, player.w, player.h);
  //Draw
  ctx.clearRect(0, 0, cnv.width, cnv.height);
  requestAnimationFrame(draw);
}


document.addEventListener("keydown", move);
function move(event) {
    console.log(event.code);
  if (event.code === 39) {
    player.x = player.x + 50;
  } else if (event.code === 37) {
    player.x = player.x - 50;
  } else if (event.code === 40) {
    player.x = player.y - 50;
  } else if (event.code === 38) {
    player.x = player.y + 50;
  }
}

Answer №1

Remember, when dealing with the event.code, it is important to note that it is a DOMString, not a number like event.keyCode.

For example, if you press the left arrow key, you should expect event.keyCode === 37 and event.code === 'ArrowLeft' to be true.

If you encounter any issues, consider changing either code to keyCode, or adjusting the comparison values for event.code. This small tweak should solve your problem :)

Cheers!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue with accessing container client in Azure Storage JavaScript library

When working on my Angular project, I incorporated the @azure/storage-blob library. I successfully got the BlobServiceClient and proceeded to call the getContainerClient method, only to encounter this error: "Uncaught (in promise): TypeError: Failed ...

Learn how to successfully upload an image using React and Node without having to rely on

I am currently exploring file uploading in react/node. Instead of passing files directly into the API request, I am passing them within the body of the request. Here is a snippet of my react code: import React, { Component } from 'react'; import ...

Sort div elements based on checkbox filters

I have a set of checkboxes that I want to use for filtering purposes. <div class="filter"> <div class="checkbox"> <label><input type="checkbox" rel="canada"/>Canada</label> </div> <div class="chec ...

The feature of option display is not supported on Safari browser

I am facing an issue with the functionality of two dropdown menus. The options in the second dropdown are supposed to be shown based on the selection made in the first dropdown. While this feature works perfectly in Chrome, it seems to be malfunctioning i ...

How do I select the first element with class "cell" in D3, similar to jQuery's $(".cell:first")?

I have attempted this: d3.select(".cell:first") d3.selectAll(".cell").filter(":first") d3.selectAll(".cell").select(":first") but unfortunately, none of these methods are effective. ...

Guide to eliminating hashtags from the URL within a Sencha web application

I'm currently developing a Sencha web application and I need to find a way to remove the "#" from the URL that appears after "index.html". Every time I navigate to a different screen, I notice that the URL looks like this: ...../index.html#Controller ...

Improve the way you manage return statements

Here is the function in question: const checkifHaveBomb = (column, row) => { let isBomb = false activeBombContainer.forEach(element => { if (element.column === column && element.row === row) { ...

Socket.io is most effective when reconnecting

I am currently in the process of developing a React application that connects to a Node.js API and I am trying to integrate the Socket.io library. Following various online tutorials, my code now looks like this: API: import express from 'express&apo ...

Having issues with my JavaScript timer - seeking assistance in troubleshooting the problem

Trying to set a timer for my little game, but facing some difficulties. The timer causes the balance to randomly increase from 0 to 13000 + some extra amount. <script> var coins = 0; var speed = 1; </script> <center> <h4> ...

Exploring the Dynamic Display of Nested JSON Objects in Angular 6

Struggling with a complex issue and feeling lost on how to approach it. I'm currently working with Angular 6. The challenge at hand involves handling JSON data in my project. While accessing simple data like "id" or "certificate" is easy, I'm en ...

The issue of Bootstrap dynamic tabs retaining their active state even after switching tabs, leading to elements being stacked

For my university project, I am developing a website that resembles a text editor using Bootstrap as the framework. To create the website menus, dynamic tabs have been utilized. The following is the code snippet I have implemented: <!--Bootstrap ...

Angular Dom does not update when invoking a function within a separate component

Greetings everyone! I am facing a situation where one component (let's name it recipe component) has a reference to another component (named grocery component). The method in my recipe component uses the reference to the grocery component to call a s ...

Is it possible to send an AJAX request to a Django view that might result in a redirect?

Query I encountered an issue while attempting to access a specific Django view through AJAX. This particular view redirects users if they haven't authorized the site with Google. I suspect the problem arises from redirecting "within" a view requested ...

Dealing with asynchronous tasks in JavaScript

I am currently delving into the world of Node development and struggling to grasp the asynchronous nature of JavaScript and Node.js. My project involves creating a microservices backend web server using Express in the gateway service, which then translates ...

Ways to address the CORS problem in an ajax function without relying on json

When I run my ajax function: function fn_nextitem(sliderNo){ $.get("/index.php?op=ajax", {slide_no:sliderNo},function(resp) { if (resp) { $('#Div').append(resp); } else { } } This is how my ph ...

What is the best way to create a button that will trigger a modal window to display a message?

I am looking to create a button that will open a modal window displaying a message. However, when I tried to add a label and viewed the page, the desired window appeared on top of the rest of the content. But unfortunately, clicking the button did not prod ...

Can a blob file be transformed into base64Data using Javascript specifically in Ionic and Angular frameworks?

https://i.stack.imgur.com/3aMyx.png[ async FileZip() { const code = await fetch("./assets/input.txt") var blob = await downloadZip([code]).blob() console.log(blob); function blobToBase64(blob: Blob): Observable<string> { r ...

Customizing the Header Navigation in Vue App.vue Across Various Views

Struggling to find the best approach for managing a header navigation in Vue 2 using Vuex with VueRouter. The main issue is creating a dynamic 'header' type navigation in App.vue. <div id="nav"> <!--Trying to create a dynamic ...

Concentrate on what comes next

Within my JavaScript code, I have the following line: $('input')[$('input').index(this)+9].focus(); I intended for this line to focus on the next element. However, when it executes, I encounter the following error: Error: [$rootSc ...

Remove the attribute from the element in the ng-repeat loop

Here is my ng-repeat code snippet: <th ng-repeat="field in tableFields" translate="{{field.headerTitle | translate}}" ts-criteria="{{field.sortable ? field.fieldKey : null}}"> <label class="i-checks" ng-if="field.isCheckbox"> & ...