所以,我设法为我的项目制作输入代码
function showText(stringTuts,stringKey) //this is the class for showing the text
{
ctx.font = "20px Arial";
ctx.fillText(stringTuts,503,150);
ctx.fillText(stringKey,713,150);
}
window.addEventListener("keypress",onKeyPress);
function onKeyPress(e)
{
console.log(e.keyCode);
var str = String.fromCharCode(e.keyCode);
console.log(str+":"+e.keyCode);
var tune = new Audio();
if (e.keyCode == 113) //this code is for the input
{
tune = new Audio("Assets/Tune/C.mp3"); //play the sound when key is pressed
tune.play();
stringTuts = "C";
stringKey = "Q";
showText(stringTuts,stringKey); //showing the text what key is being pressed right now
}
else if ( e.keyCode == 119)
{
tune = new Audio("Assets/Tune/D.mp3");
tune.play();
stringTuts = "D";
stringKey = "W";
showText(stringTuts,stringKey);
}
else if ( e.keyCode == 101)
{
tune = new Audio("Assets/Tune/E.mp3");
tune.play();
stringTuts = "E";
stringKey = "E";
showText(stringTuts,stringKey);
}
else if (e.keyCode == 114)
{
tune = new Audio("Assets/Tune/F.mp3");
tune.play();
stringTuts = "F";
stringKey = "R";
showText(stringTuts,stringKey);
}
else if (e.keyCode == 116)
{
tune = new Audio("Assets/Tune/G.mp3");
tune.play();
stringTuts = "G";
stringKey = "T";
showText(stringTuts,stringKey);
}
}
我的问题是,当我成功按下Q' Q'按钮,showText()函数可以显示正在按下的键,但是如果我按下了W'它将显示该键而不删除' Q'按钮文字。我尝试了一些方法,比如在onKeyPress(e)函数中创建临时变量,但它根本没有帮助。有人可以帮我解决这个问题吗?感谢
答案 0 :(得分:2)
这是因为在向其添加新文本之前,您没有清除画布。只需将ctx.clearRect(0, 0, widthOfCanvas, heightOfCanvas);
添加到showText()
函数的开头。
有关ctx.clearRect
函数https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/clearRect