I want to create a canvas on my web page that will let the users type their name in "Journal" font. I have the following code, but, as you can see in dokeyDown, I can only type "Z". How can I make it for all the alphabets so that users can type their full name. Do I need to specify keyId for each alphabet or is their any easier way? Below is what I have
<div id="my_painter">
<canvas id="canvas" tabindex="0"></canvas>
</div>
<script>
var tempContext = null;
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.addEventListener('keydown', doKeyDown, true);
canvas.focus();
window.addEventListener('keydown', doKeyDown, true);
}
function doKeyDown(e) {
var keyID = e.keyCode ? e.keyCode : e.which;
if (keyID === 90) {
tempContext.fillText("A", 100, 60);
e.preventDefault();
}
}
Any help will be greatly appreciated
2
Answers
This will allow you to show any character
Instead of extracting the
.keyCode
, get the.key
, which is the character itself. Then you can display that character easily.To allow a series of characters to show, you will want to move the cursor right at each step, e.g. by advancing it by a few pixels each time.
For this to work well, you are better off not using Journal, but rather choosing a monospaced font such as
Courier New
.You can use the
String.fromCharCode()
method to convert the keyID variable into a character. In that way, you don’t need to match the code for each key.A listener on canvas is already added so I commented on the listener on the window otherwise every character will get printed twice.