1

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
wanna_coder101
  • 508
  • 5
  • 19
  • And the Roboto font is installed on the system natively in both cases? – Kaiido Aug 14 '23 at 07:46
  • Hmm, just checked that macosx doesn't have the roboto font installed? I tried the register fonts before but the text width wasn't fixed. Perhaps I'll try again and see what happens. – wanna_coder101 Aug 14 '23 at 22:14
  • Tried using the font PT Sans, this is a system font on macosx, running serverless offline/lambda still gives the same issue with different width sizing. – wanna_coder101 Aug 14 '23 at 23:44

0 Answers0