wrap

by aio350

HTML

<canvas width="300" height="300" style="border: 1px dotted #222"></canvas>

CSS

body {
  margin: 0;
  height: 100vh;
  background: radial-gradient(circle, skyblue, steelblue);
  display: flex;
  justify-content: center;
  align-items: center;
}

JavaScript

const canvas = document.querySelector('canvas')
const $ = canvas.getContext('2d')

function wrapText($, text, x, y, maxWidth, lineHeight) {
  const words = text.split(' ')
  let line = ''

  for (let n = 0; n < words.length; n++) {
    const testLine = line + words[n] + ' '
    const metrics = $.measureText(testLine)
    const testWidth = metrics.width

    if (testWidth > maxWidth && n > 0) {
      $.fillText(line, x, y)
      line = words[n] + ' '
      y += lineHeight
    } else line = testLine
  }
  $.fillText(line, x, y)
}

const maxWidth = 295
const lineHeight = 25
const x = canvas.width / 2
const y = 80
const text = 'Мы — источник веселья и скорби рудник. Мы — вместилище скверны и чистый родник. Человек, словно в зеркале мир, — многолик. Он ничтожен — и он же безмерно велик!';

$.font = '20pt Calibri'
$.fillStyle = '#222'
$.textAlign = 'center'
wrapText($, text, x, y, maxWidth, lineHeight)