Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

161
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!