I have a canvas with custom styling. In the center of the canvas is a single letter. Please see the code below for reference. The goal is to change the displayed letter by pressing a key on the keyboard. For instance:
Letter A is centered in the canvas: Pressing the g-key should change it to the letter G (uppercase)
Based on my current understanding, I believe I need to utilize the "keyup" method along with "document.addEventListener". I am currently learning JavaScript through a course, but I've noticed that the course heavily relies on certain libraries, which I personally do not prefer. While I understand the benefits, I would like to establish a foundation in pure JS before delving into unfamiliar libraries. Any guidance on this matter would be greatly appreciated.
body {
background-color: #000000;
}
canvas {
padding: 0;
margin: auto;
display: block;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
background-color: #111416;
border: 10px solid #a60000;
border-style: double;
box-shadow: 0 0 20px 5px #a60000;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<link rel="stylesheet" href="canvas.css">
<canvas id="myCanvas" width="800" height="800"></canvas>
<script>
// Obtain the canvas element by its ID
var canvas = document.getElementById("myCanvas");
// Provide the 2D rendering context for drawing on the canvas
var context = canvas.getContext("2d");
// Retrieve the width and height of the canvas element
var canvW = document.getElementById("myCanvas").width;
var canvH = document.getElementById("myCanvas").height;
let text = "f";
context.fillStyle = "#a60000";
context.font = "700px serif";
// Measure the dimensions of the letter based on the font style
// Automatically center the letter within the canvas regardless of size
// Display the size of the letter
const metrics = context.measureText(text);
const mx = metrics.actualBoundingBoxLeft * -1;
const my = metrics.actualBoundingBoxAscent * -1;
const mw = metrics.actualBoundingBoxLeft + metrics.actualBoundingBoxRight;
const mh = metrics.actualBoundingBoxAscent + metrics.actualBoundingBoxDescent;
const x = (canvW -mw) *0.5 - mx;
const y = (canvH - mh) *0.5 - my;
context.save();
context.translate(x, y);
context.beginPath();
context.rect(mx, my, mw, mh);
context.stroke();
context.fillText(text, 0, 0);
context.restore();
const onKeyUp = (e) => {
text = e.key.toUpperCase();
manager.render();
};
document.addEventListener("keyup", onKeyUp);
</script>
</body>
</html>