I have the following code on my razor page. When I click the backspace key then it starts typing backspace. below is the screen shot:
below is the JavaScript code:
<script>
var tempContext = null;
var x = 100
window.onload = function () {
var canvas = document.getElementById("canvas");
console.log(canvas.parentNode.clientWidth);
canvas.width = canvas.parentNode.clientWidth;
canvas.height = canvas.parentNode.clientHeight;
tempContext = canvas.getContext("2d");
tempContext.fillStyle = "blue";
tempContext.font = "20px Journal";
canvas.focus();
window.addEventListener('keydown', doKeyDown, true);
}
function doKeyDown(e) {
tempContext.fillText(e.key, x, 60);
x += 9
e.preventDefault();
}
</script>
below is the canvas:
<div id="my_painter">
<canvas id="canvas" tabindex="0"></canvas>
</div>
any help will be greatly appreciated.
2
Answers
I am writing this answer as per my response to your this question.
To make the backspace key work, you need to do the following things-
String.fromCharCode(keyID)
to convert the pressed key’s key code into the character otherwise when you press any special key it will print it as an exact character like "TAB" or "BACKSPACE" etc.Here is a working demo where I added the necessary comments to explain the code-
The reason why it writes “Backspace” is because you’ve told the program to display the name of any character pressed.
The solution is quite simple though. You just need to detect if backspace is pressed and then remove the last character. The problem with your current code is you’re not storing the characters, which makes this almost impossible.
I’ve modified the code for you below. The comments should point you in the right direction.