Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

168
Visualizações
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?

about 4 years ago · Juan Pablo Isaza
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda