KeyboardEvent.code プロパティは、 (キー入力によって入力された文字ではなく) キーボード上の物理的なキーを表します。つまり、このプロパティはキーボードレイアウトや修飾キーの状態によって変更される前の値を返します。


このプロパティは、キーに関連付けられている文字ではなく、入力デバイス上の物理的な位置に基づいてキー入力を扱いたいときに役立ちます。これは特に、キーボードをゲームパッドのように使いたい場合などに有用です。ただし、 KeyboardEvent.code で報告された値を用いてキー入力で生成される文字を判断するべきではありません。キーコード名がキー上に印刷されている実際の文字や、キーが押されたときにコンピューターが生成する文字と一致するとは限らないからです。

例えば、返ってきた code が "KeyQ" は QWERTY レイアウトのキーボードでは Q キーですが、同じ Dvorak キーボードでは同じ code の値が ' キーを表し、 AZERTY キーボードでは A キーを表すものでもあります。したがって、すべてのユーザーが特定のキーボードレイアウトを使用しているわけではないため、 code の値を用いてユーザーが認識しているキーの名前が何であるかを特定することはできません。

キーイベントに対応する文字が何であるかを判別するには、、代わりにKeyboardEvent.key プロパティを使用してください。


Windows, Linux, macOS におけるコード値は、 KeyboardEvent: コード値 (en-US)ページにあります。

KeyboardEvent の使用例


<p>Press keys on the keyboard to see what the KeyboardEvent's key and code
   values are for each one.</p>
<div id="output">


#output {
  font-family: Arial, Helvetica, sans-serif;
  border: 1px solid black;


window.addEventListener("keydown", function(event) {
  let str = "KeyboardEvent: key='" + event.key + "' | code='" +
            event.code + "'";
  let el = document.createElement("span");
  el.innerHTML = str + "<br/>";

}, true);


キー入力をサンプルコードに取得させるために、キーを入力する前に output ボックスをクリックしてください。


This example establishes an event listener for keydown (en-US) events which handles keyboard input for a game which uses the typical "WASD" keyboard layout for steering forward, left, backward, and right. This will use the same four keys physically regardless of what the actual corresponding characters are, such as if the user is using an AZERTY keyboard.


<p>Use the WASD (ZQSD on AZERTY) keys to move and steer.</p>
<svg xmlns="" version="1.1" class="world">
  <polygon id="spaceship" points="15,0 0,30 30,30"/>


.world {
  margin: 0px;
  padding: 0px;
  background-color: black;
  width: 400px;
  height: 400px;

#spaceship {
  fill: orange;
  stroke: red;
  stroke-width: 2px;


The first section of the JavaScript code establishes some variables we'll be using. shipSize contains the size of the ship the player is moving around, for convenience. position is used to track the position of the ship within the play field. moveRate and turnRate are the number of pixels forward and backward each keystroke moves the ship and how many degrees of rotation the left and right steering controls apply per keystroke. angle is the current amount of rotation applied to the ship, in degrees; it starts at 0° (pointing straight up). Finally, spaceship is set to refer to the element with the ID "spaceship", which is the SVG polygon representing the ship the player controls.

let shipSize = {
  width: 30,
  height: 30

let position = {
  x: 200,
  y: 200

let moveRate = 9;
let turnRate = 5;

let angle = 0;

let spaceship = document.getElementById("spaceship");

Next comes the function updatePosition(). This function takes as input the distance the ship is to be moved, where positive is a forward movement and negative is a backward movement. This function computes the new position of the ship given the distance moved and the current direction the ship is facing. It also handles ensuring that the ship wraps across the boundaries of the play field instead of vanishing.

function updatePosition(offset) {
  let rad = angle * (Math.PI/180);
  position.x += (Math.sin(rad) * offset);
  position.y -= (Math.cos(rad) * offset);

  if (position.x < 0) {
    position.x = 399;
  } else if (position.x > 399) {
    position.x = 0;

  if (position.y < 0) {
    position.y = 399;
  } else if (position.y > 399) {
    position.y = 0;

The refresh() function handles applying the rotation and position by using an SVG transform.

function refresh() {
  let x = position.x - (shipSize.width/2);
  let y = position.y - (shipSize.height/2);
  let transform = "translate(" + x + " " + y + ") rotate(" + angle + " 15 15) ";

  spaceship.setAttribute("transform", transform);

Finally, the addEventListener() method is used to start listening for keydown (en-US) events, acting on each key by updating the ship position and rotation angle, then calling refresh() to draw the ship at its new position and angle.

window.addEventListener("keydown", function(event) {
  if (event.defaultPrevented) {
    return; // Do nothing if event already handled

  switch(event.code) {
    case "KeyS":
    case "ArrowDown":
      // Handle "back"
    case "KeyW":
    case "ArrowUp":
      // Handle "forward"
    case "KeyA":
    case "ArrowLeft":
      // Handle "turn left"
      angle -= turnRate;
    case "KeyD":
    case "ArrowRight":
      // Handle "turn right"
      angle += turnRate;


  // Consume the event so it doesn't get handled twice
}, true);

Try it out

To ensure that keystrokes go to the sample code, click inside the black game play field below before pressing keys.

There are several ways this code can be made better. Most real games would watch for keydown (en-US) events, start motion when that happens, and stop the motion when the corresponding keyup (en-US) occurs, instead of relying on key repeats. That would allow both smoother and faster movement, but would also allow the player to be moving and steering at the same time. Transitions or animations could be used to make the ship's movement smoother, too.


仕様書 状態 備考
UI Events
KeyboardEvent.code の定義
草案 初回定義、コード値を含む。


BCD tables only load in the browser