How to Measure text width in both node-canvas and canvas, currently gives wildly different results

138 Views Asked by At

I'm trying to get the width of text to reduce the font size to fit an element.

When using measureText, the browser text width is 570-600 whilst the node-canvas implementation is 350. The max width is 360.

Because of this difference, the browser version would reduce the font size to 28, whilst the node version leaves the font size at 46.

  // Node Canvas implementation
  var cv = createCanvas(0, 0);
  var ctx = cv.getContext('2d');
    
  ctx.font = `normal 48px Roboto`;
  ctx.fillStyle = '#000000';
  ctx.textAlign = 'left';
  
  const measureText =  ctx.measureText('Seraphina Aurelia Everhart')
  const textWidth = measureText.width;
  
  console.log(textWidth);
  // Browser = 570 - 600ish
  // Node = 336

JSFiddle of browser canvas

Does anyone know how to get measureText, or a way to measure text in both node-canvas and browser canvas with roughly the same results? This is only for chrome (electron).

Some hacks I can think of would be create a canvas, draw the text and set the canvas width to the text width. Thus the canvas width is the text width.

Versions

Node: 18 lts
node-canvas: 2.11.2
Serverless offline: 3.31.0
Using lambda


Macosx: 13.4.1
0

There are 0 best solutions below