O
O
olezhenka2018-03-16 01:23:07
JavaScript
olezhenka, 2018-03-16 01:23:07

How to adjust the font size depending on the number of characters and the height of the container?

I need the following:
I have a specific height and width in which I want to fit text, and I need to do this so that the text takes up all the given space.
For example:
width and height are 500 each, the following string is given: AaaAaA
I need to get the font size so that the entire width is occupied by text.
Here's the shit I got:

function fitSizeFont(canvas, ctx, text)
{
  console.log("\n");
  let width = canvas.width * 0.8;
  let height = canvas.height * 0.5;
  console.log('ШИРИНА КАРТИНКИ ', width);
  console.log('ВЫСОТА КАРТИНКИ', height);
  console.log("\n");

  let fontSize = Math.round(canvas.height * 0.05);
  console.log('Размер шрифта ДО ', fontSize);

  ctx.font = `${fontSize}px "${fontFamily}"`

  let textWidth = ctx.measureText(text).width;
  console.log('Ширина текста относительно размера шрифта ДО ', textWidth);

  let countWrap = textWidth / width;
  console.log('Количество текущих переносов строк ', countWrap);

  let heightWrap = countWrap * fontSize;
  console.log('Высота обертки ', heightWrap);

  let ratio = height / heightWrap;
  console.log('Высота картинки / Высота обертки ', ratio);

  fontSize = Math.round(fontSize * ratio);
  console.log('Размер шрифта ПОСЛЕ ', fontSize);

  textWidth = ctx.measureText(text).width;
  console.log('Ширина текста относительно размера шрифта ПОСЛЕ ', textWidth);

  ctx.font = `${fontSize}px "${fontFamily}"`;

  console.log("\n");

  return fontSize;

}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
twobomb, 2018-03-16
@twobomb

Possibly something like this . If the text in one line should be

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question