2 years ago
#31756
Michael Moreno
How to calculate pixel width of given letter
I'm attempting to implement the ability to draw text to the screen on a basic 2D plane, using only HTML Canvas and JavaScript.
I start by setting up the canvas.
const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d");
I have a keydown
event listener that appends to an array whatever characters I enter.
let characters = []
document.onkeydown = function(event) {
if (event.key.length === 1) {
characters.append(event.key)
}
}
I want to draw each character onto the canvas.
let x,y = 0;
characters.forEach(char => {
ctx.beginPath()
ctx.font = "20px Arial"
ctx.fillText(char, x, y)
x += someValue // this needs to be calculated based on character pixel width
})
To avoid drawing all the characters at the same spot and overlapping, I have to increment the x
coordinate by some value each iteration. This can't be a constant value, because characters differ in their pixel width ('O' is wider than 'I').
I need a way to know how much pixel space a character will take up, to determine what x
coodinate to draw the subsequent character at.
I'm not looking for an HTML/JS specific answer. I want to know what the general computer science approaches are to rendering characters with correct spacing to a graphical context. i.e, how does HTML itself do it under the hood?
javascript
user-interface
character
2d
low-level
0 Answers
Your Answer