在此代碼中,出於某種原因,我需要雙擊該鍵才能使文本走向我想要的方向。如果我不這樣做,文本將繼續沿着前一個方向前進。我現在正在爲此尋找一個解決方案,現在我似乎無法找到正確的代碼。Javascript:Onkeydown,將文本移動到某個方向,但需要按兩次
下面的代碼: https://jsfiddle.net/MindZeroJ5/4cykaLs8/
HTML:
<canvas id="canvas" style="border:1px solid black;" width="500" height="500" ></canvas>
JAVASCRIPT:
"use strict";
var c = document.getElementById("canvas"),
ctx = c.getContext("2d"),
y,
x,
kpd,
kcd,
kpu,
kcu,
HEIGHT,
WIDTH;
x = 50;
y = 50;
HEIGHT = 500;
WIDTH = 500;
ctx.font = "20px Georgia";
ctx.fillText("Hello World!", x, y);
function movetextup() {
ctx.clearRect(0, 0, HEIGHT, WIDTH);
y -= 10;
ctx.fillText("Hello World!", x, y);
console.log(x + " " + y);
}
function movetextdown() {
ctx.clearRect(0, 0, HEIGHT, WIDTH);
y += 10;
ctx.fillText("Hello World!", x, y);
console.log(x + " " + y);
}
function movetextleft() {
ctx.clearRect(0, 0, HEIGHT, WIDTH);
x -= 10;
ctx.fillText("Hello World!", x, y);
console.log(x + " " + y);
}
function movetextright() {
ctx.clearRect(0, 0, HEIGHT, WIDTH);
x += 10;
ctx.fillText("Hello World!", x, y);
console.log(x + " " + y);
}
document.onkeydown = function (e) {
kpd = String.fromCharCode(e.keyCode);
kcd = e.keyCode;
console.log('pressed ' + kpd);
if (kpu == "W") {
movetextup();
}
if (kpu == "S") {
movetextdown();
}
if (kpu == "A") {
movetextleft();
}
if (kpu == "D") {
movetextright();
}
};
document.onkeyup = function (e) {
kpu = String.fromCharCode(e.keyCode);
kcu = e.keyCode;
console.log('unpressed ' + kpu);
};
謝謝!