Javascript HTML 5画布输入被覆盖

Javascript HTML 5画布输入被覆盖,javascript,html5-canvas,Javascript,Html5 Canvas,因此,我设法为我的项目生成输入代码 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); funct

因此,我设法为我的项目生成输入代码

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”按钮时,showText()函数可以显示正在按下的键,但如果我按下“W”,它将显示该键而不删除“Q”按钮文本。我尝试过一些方法,比如在onKeyPress(e)函数中设置temp变量,但根本没有帮助。有人能帮我想办法解决这个问题吗?谢谢

这是因为在向画布添加新文本之前,您没有清除画布。只需添加
ctx.clearRect(0,0,canvas的宽度,canvas的高度)
showText()
函数的开头


关于
ctx.clearRect
函数的其他信息

您必须使用Thank it清理画布修复此案例,我以前尝试添加clearRect(),但似乎我放错了方向。没问题,我很高兴能提供帮助。编辑:顺便说一下,如果它是正确的,你可能想考虑接受这个答案,以便其他人能在将来找到它。