このコードでは、何らかの理由でテキストを希望の方向に移動するためにキーを2回押す必要があります。もし私がそれをしなければ、テキストはそれが入った前の方向に向かい続けるでしょう。私は2時間のための解決策を探していました、私は配置する正しいコードを見つけることができないようです。 https://jsfiddle.net/MindZeroJ5/4cykaLs8/Javascript:Onkeydown、特定の方向にテキストを移動しますが、2回押す必要があります
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);
};
おかげ
は、ここでは、コードです!