Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

160
Vistas
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 la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda