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

387
Vistas
Canvas: Text width is not equal to the summary of the widths of its characters

In most cases, they are the same. But I found this special case, it is different when I change the order of characters.

const ctx = document.createElement('canvas').getContext('2d');
const tw = text => ctx.measureText(text).width;

tw('Tr') - tw('T') - tw('r') // -0.3662109375
tw('rT') - tw('T') - tw('r') // 0

Can anyone tell me the rules of this behavior? Thank you!

about 4 years ago · Santiago Gelvez
1 Respuestas
Responde la pregunta

0

This is because of kerning, which is how some characters will be more or less close to their neighbors. This will depend on the font used, and the characters shown.

Chrome recently added support for a .fontKerning property that we can use to disable this,

if ("fontKerning" in CanvasRenderingContext2D.prototype) {
  const canvas = document.querySelector("canvas");
  const ctx = canvas.getContext("2d");
  ctx.textBaseline = "middle";
  ctx.font = "30px sans-serif";
  ctx.fillText("AV", 0, 30);
  console.log("with kerning", ctx.measureText("AV").width);
  ctx.fontKerning = "none";
  console.log("without kerning", ctx.measureText("AV").width);
  ctx.fillText("AV", 0, 60);
  console.log("sum of chars", ctx.measureText("A").width + ctx.measureText("V").width);
}
else {
  console.log("your browser doesn't support setting fontKerning");
}
<canvas></canvas>

and you could use mono-space fonts to avoid it, but that would still not be bullet proof because even then some glyphs just can't be measured as you did.

So the best is to measure the full text that you want to measure.

about 4 years ago · Santiago Gelvez Denunciar
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