【问题标题】:Forward keyboard keydown events from html5 textbox to game canvas将键盘按键事件从 html5 文本框转发到游戏画布
【发布时间】:2019-11-12 15:16:15
【问题描述】:

如何将移动浏览器需要发送到文本框的所有键盘击键转发到我的游戏画布中?

我必须在我的游戏下方添加这种输入框,以便输入框触发手机屏幕上的键盘,并且游戏在 iPhone 上运行正常,但在 Android 上不行。游戏当然可以使用物理键盘。

<input value="click here" style="font-size: 22px;" autocorrect="off" autofocus type='text' id='foo'><div onclick='$("#foo").focus();'>click here</div>

【问题讨论】:

  • 只需在文本框中添加一个input 事件侦听器,然后在处理函数中执行任何操作。到目前为止,您尝试过什么吗?如果是,请在问题中提出。
  • 对于 IOS,我的游戏似乎可以获取键盘事件;但 Android 不会将事件传递到游戏画布。
  • 你能解释一下你的游戏是如何运作的吗?文本框在做什么?为什么会成为焦点?您是否将 keydown 侦听器附加到 canvas 元素,它适用于 iOS 但不适用于 Android?现在这个问题可能很快就会结束。
  • 谢谢克里斯,请用手机点击这里看看游戏和它下面的文本框是如何工作的,点击游戏红色按钮后需要点击一个文本框,这使得iPhone虚拟键盘可以使用游戏rebrand.ly/ut2nh8
  • 嗯,这花了一些时间,但我终于明白了(我想)。来源:codesandbox.io/s/intelligent-margulis-kwvxf Live URL:kwvxf.csb.app 代码创建了一个新事件,我手动设置了它的.key,所以问题是画布监听器正在寻找哪个属性。

标签: javascript android


【解决方案1】:

由于显然无法转发原始事件,我的方法是创建自己的事件并将其分派到画布上。 为了隐藏用户正在点击&lt;input&gt; 的事实,我在顶部放置了一个按钮并使其忽略指针事件。我还必须始终在文本字段中保留一个字符,以防止 Android 键盘返回大写字母。

const canvas = document.querySelector("#app canvas");
const link = document.querySelector("#app a");
const input = document.querySelector("#app input");
const output = document.querySelector("#app pre");

canvas.addEventListener("keydown", e => {
  // console.log("key:", e.key);
  output.textContent += e.key;
});

input.addEventListener("focus", function() {
  setTimeout(() => {
    link.style.display = "none";
    input.value = "a";
  }, 0);
});

input.addEventListener("keyup", function(e) {
  const key = this.value[1];
  const keyCode = key && key.charCodeAt(0);
  const ev = new KeyboardEvent("keydown", {
    key,
    keyCode
  });
  canvas.dispatchEvent(ev);
  setTimeout(() => {
    input.value = "a";
  }, 0);
});
body {
  font-family: sans-serif;
  text-align: center;
}

canvas {
  display: block;
  box-shadow: 0 0 5px 0 black;
  width: 60%;
  margin: 0 auto;
  height: 120px;
}

#app {
  position: relative;
}

#textfield {
  position: absolute;
  left: 0;
  width: 100%;
  top: 40%;
  text-align: center;
}

#textfield * {
  width: 70px;
  height: 40px;
  position: absolute;
  margin-left: -35px;
}

#textfield a {
  color: white;
  border-radius: 5px;
  background-color: red;
  box-sizing: border-box;
  padding: 0.5em;
  pointer-events: none;
  z-index: 1;
}

#textfield input {
  cursor: pointer;
  width: 70px;
  opacity: 0;
}
<div id="app">
  <canvas></canvas>
  <p id="textfield">
    <a href="">Play</a>
    <input />
  </p>
  Canvas keydown listener output:
  <pre></pre>
</div>

【讨论】:

  • 干得好,但是我在输入框中添加了一些参数以避免自动输入等。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-08-01
  • 2018-08-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-12
  • 2010-09-29
相关资源
最近更新 更多